Groovy XMLSlurper - 搜索特定节点 [英] Groovy XMLSlurper - searching sepecific node

查看:138
本文介绍了Groovy XMLSlurper - 搜索特定节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用Groovy的XMLSlurper找到一个特定的节点。条件应该是子节点的文本/值必须匹配。在下面的例子中,我想搜索年份为'2003'且价格为'39.95'的图书节点。

I need to find a specific node with Groovy's XMLSlurper. The condition should be that the text/value of the children nodes have to match. In the following example I want to search for a book node where the year is '2003' and the price is '39.95'.

<bookstore name="Store A">
  <employee>
      <id>546343</id>
      <name>Dustin Brown</name>
  </employee>
  <employee>
      <id>547547</id>
      <name>Lisa Danton</name>
  </employee>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
<bookstore name="Store B">
...
</bookstore>


推荐答案

鉴于:

def xml = '''<stores>
  <bookstore name="Store A">
      <employee>
          <id>546343</id>
          <name>Dustin Brown</name>
      </employee>
      <employee>
          <id>547547</id>
          <name>Lisa Danton</name>
      </employee>
      <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
      </book>
      <book category="children">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
      </book>
      <book category="web">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
      </book>
  </bookstore>
  <bookstore name="Store B">
  </bookstore>
</stores>'''

然后

Then

new XmlSlurper().parseText(xml).bookstore.book.findAll { it.year == '2003' && it.price == '39.95' }

这篇关于Groovy XMLSlurper - 搜索特定节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆