使用 groovy 遍历每个 xml 节点,打印每个节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15077592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through EACH xml node with groovy, printing each node
提问by user2109043
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..)
我面临的问题是,我不能简单地使用此代码分别访问每个节点……它正在打印所有内容,而我真正想做的是将每个节点收集到地图中,然后进行询问/transform 地图中的一些键/值对并替换它们(在路上,我知道..)
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
感谢致敬
回答by Dave Newton
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

