groovy打印xml中元素的路径和值 [英] groovy Print path and value of elements in xml
问题描述
我有以下xml:
<list>
<cars>
<model>2012</model>
<make>GM</make>
</cars>
</list>
我想将这些值打印为path:value,如下所示.
I want to print these values as path:value as shown below.
list/cars/model : 2012
list/cars/make : GM
我该如何实现?我尝试了name()
方法,但它仅打印子项的名称.我想将整个路径打印到元素.
How can I achieve this? I tried the name()
method but it only prints the name of child item. I want to print the whole path till the element.
我只能使用xmlSlurper解析器来做到这一点.
I can only use xmlSlurper parser to do this.
谢谢.
推荐答案
def xml = '''
<list>
<cars>
<model>2012</model>
<make>GM</make>
<color>Gold</color>
</cars>
</list>
'''
def item = new XmlSlurper().parseText(xml)
item.'**'.inject([]) { acc, val ->
def localText = val.localText()
acc << val.name()
if( localText ) {
println "${acc.join('/')} : ${localText.join(',')}"
acc = acc.dropRight(1) // or acc = acc[0..-2]
}
acc
}
这将按要求打印.上面是在树上使用depthFirst()
搜索并使用inject(只是不突变其他列表)并查找 localText()
,指示叶节点的值,然后打印路径和值.该路径已累积在用于注入的列表中.简单的join()
将提供所需的格式.
This would print as required. Above is using a depthFirst()
search on the tree and using inject (just not to mutate any other list) and looks for localText()
. If localText()
is encountered indicating the value of the leaf node, then print the path and the value. The path has been accumulated in a list which was used in inject. A simple join()
would give the required format.
Above已在Groovy 2.4.5中成功测试.如果localText()
在NodeChild
中不可用,则可能是Groovy的版本早于2.3.0的原因,因为该方法自2.3.0起已添加
Above has been tested successfully in Groovy 2.4.5. If localText()
is not available in NodeChild
then a version of Groovy older than 2.3.0 would be reason because that method has been added since 2.3.0
这篇关于groovy打印xml中元素的路径和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!