简体   繁体   English

使用groovy遍历每个xml节点,打印每个节点

[英]Iterate through EACH xml node with groovy, printing each node

I have a very simple ( I thought ) xml file like this... 我有一个非常简单的(我认为)像这样的xml文件...

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<Things>
<thing indexNum='1'>
  <a>123</a>
  <b>456</b>
  <c>789</c>
</thing>
<thing indexNum='2'>
  <a>123</a>
  <b>456</b>
  <c>789</c>
</thing>
</Things>

The issue I'm facing is that I cannot simply get at each node separately with this code... it is printing ALL of the things, and what I'm really attempting to do is to collect each node into a map, then interrogate/transform some key/value pairs in the map and replace them (way down the road, I know..) 我面临的问题是我不能简单地用这个代码分别得到每个节点...它正在打印所有的东西,我真正想要做的是将每个节点收集到一个地图中,然后询问/转换地图中的一些键/值对并替换它们(我知道......)

Here's my horrendous code... any chance someone can set me in the right direction? 这是我可怕的代码......任何人都有可能让我朝着正确的方向前进?

def counter = 0

Things.thing.each { tag ->
  counter++
  println "\n--------------------------------  $counter  ------------------------------------"

  Things.thing.children().each { tags ->
    println "$counter${tags.name()}: $tags"
    return counter
  }
  println "\n$counter things processed...\n"
}

Would it be easier to manipulate this inside of a map? 在地图内部操纵它会更容易吗? (I generated this xml with a map in the first place, thinking that there would be some easy methods to work with the XML... I'm starting to wonder after goofing around for days and getting basically nowhere) (我首先使用地图生成了这个xml,认为有一些简单的方法可以使用XML ...我开始怀疑经过几天的闲逛并且基本上无处可去)

Thanks and Regards 感谢致敬

The reason you keep getting the inner nodes is because you incorrectly iterate over the outer list twice. 继续获取内部节点的原因是因为您错误地迭代外部列表两次。 The inner loop should iterate only over tag : 内部循环应仅在tag迭代:

doc = new XmlSlurper().parse("things.xml")
doc.thing.each { thing ->
  println "thing index: ${thing.@indexNum}"
  thing.children().each { tag ->
    println "  ${tag.name()}: ${tag.text()}"
  }
}

Output: 输出:

thing index: 1
  a: 123
  b: 456
  c: 789
thing index: 2
  a: 123
  b: 456
  c: 789

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM