简体   繁体   English

读取groovy中的xml值

[英]reading an xml value in groovy

i have checked around the site and although many people are looking for similar solutions, a solution to my specific problem has not been posted, nor has a similar question been asked. 我已经检查了整个站点,尽管许多人正在寻找类似的解决方案,但尚未发布针对我的特定问题的解决方案,也未提出类似问题。

i have an XML that looks like this: 我有一个看起来像这样的XML:

<root>
 <item1>TEXT A</item1>
 <item2>TEXT B</item2>
 <subs>
  <sub1>
   <thing property1='valueA' property2='valueB'>
    <foo>fooA</foo>
  </sub1>
  <sub2>
   <thing property1='valueC' property2='valueD'>
    <foo>fooA</foo>
  </sub2>
 </subs>
</root>

i want to get "TEXT B" 我想获得“ TEXT B”

i am thinking 我在想

def xml = new XmlParser().parseText(MY_XML_FILE)

but now how do i access "TEXT B" ?? 但是现在我该如何访问“ TEXT B”?

xml.root.item2.text

does not work. 不起作用。 any thoughts? 有什么想法吗?

There's a few things going on here: 这里发生了一些事情:

  1. Groovy's XmlParser and XmlSlurper (I recommend the latter) take an XML document wrapped in a root element (well-formed XML always exists in a root element). Groovy的XmlParser和XmlSlurper(我建议后者)采用包裹在根元素中的XML文档(格式正确的XML始终存在于根元素中)。 Groovy doesn't require you to specify the root element, so Groovy不需要您指定根元素,因此

    xml.root.item1 xml.root.item1

can become 可以变成

xml.item1

If you have many item1s, you need to access them as an array. 如果您有许多item1,则需要以数组形式访问它们。

xml.item1[0]
  1. Your XML is not well-formed. 您的XML格式不正确。 You're missing two end tags. 您缺少两个结束标签。

  2. To get the inner text of a node, use text() instead of text (it's a method). 要获取节点的内部文本,请使用text()而不是text(这是一种方法)。

Here are some excellent resources on both XmlParser and XmlSlurper . 这是XmlParserXmlSlurper上的一些优秀资源。

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

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