如何使用groovy迭代XML节点



我试图用groovy迭代xml文件以获得一些值。我发现很多人都有同样的问题,但他们使用的解决方案不适合我,或者太复杂了。我不是一个groovy开发人员,所以我需要一个我可以实现的防弹解决方案。

基本上我有一个xml响应文件,看起来像这样:(看起来很糟糕,但这是我得到的)

<Body>
<head>
<Details>
<items>
<item>
<AttrName>City</AttrName>
<AttrValue>Rome</AttrValue>
</item>
<item>
<AttrName>Street</AttrName>
<AttrValue>Via_del_Corso</AttrValue>
</item>
<item>
<AttrName>Number</AttrName>
<AttrValue>34</AttrValue>
</item>
</items>

</Details>
</head>
</Body>

我已经尝试了这个解决方案,我在这里找到StackOverflow打印值:

def envelope = new XmlSlurper().parseText("the xml above")
envelope.Body.head.Details.items.item.each(item -> println( "${tag.name}")  item.children().each {tag -> println( "  ${tag.name()}: ${tag.text()}")} }  

我得到的最好的是

ConsoleScript11$_run_closure1$_closure2@2bfec433
ConsoleScript11$_run_closure1$_closure2@70eb8de3
ConsoleScript11$_run_closure1$_closure2@7c0da10
Result: CityRomeStreetVia_del_CorsoNumber34

我也可以删除第一次println之后的所有内容,以及其中的任何内容,结果是相同的

这里我的主要目标不是打印这些值,而是从xml中推断这些值并将它们保存为字符串变量…我知道使用字符串不是最佳实践,但我现在只是需要理解。

你的代码有两个缺陷:

  1. 使用envelope.Body,您将找不到任何
  2. 如果您修复了第1条,您将遇到each(item -> println( "${tag.name}")的多个编译错误。这里使用(而不是{,这里使用未定义的tag变量。

工作代码看起来像:

import groovy.xml.*
def xmlBody = new XmlSlurper().parseText '''
<Body>
 <head>
  <Details>
<items>
<item>
<AttrName>City</AttrName>
<AttrValue>Rome</AttrValue>
</item>
<item>
<AttrName>Street</AttrName>
<AttrValue>Via_del_Corso</AttrValue>
</item>
<item>
<AttrName>Number</AttrName>
<AttrValue>34</AttrValue>
</item>
</items>
 
  </Details>
 </head>
</Body>'''
xmlBody.head.Details.items.item.children().each {tag ->
println( "  ${tag.name()}: ${tag.text()}")
}

和打印:

AttrName: City
AttrValue: Rome
AttrName: Street
AttrValue: Via_del_Corso
AttrName: Number
AttrValue: 34

最新更新