如何在 Groovy 中按标签名称查找所有 XML 元素? [英] How to find all XML elements by tag name in Groovy?

查看:18
本文介绍了如何在 Groovy 中按标签名称查找所有 XML 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 Groovy (GPath) 中的标记名称查找 XML 中的所有元素?

How I can find all elements in XML by their tag name in Groovy (GPath)?

我需要在这个文档中找到所有的car元素:

I need to find all car elements in this document:

<records>
  <first>
    <car>
      <id>378932</id>
    </car>
  </first>
  <second>
    <foo>
      <car>
       <name>audi</name>
      </car>
    </foo>
  </second>
</records>

这是我尝试过但失败的方法:

This is what I tried and failed:

def xml = new XmlSlurper().parse(file)
assert xml.car.size() == 2

推荐答案

这是它的工作原理:

def xml = new XmlSlurper().parse(file)
def cars = xml.depthFirst().findAll { it.name() == 'car' }
assert cars.size() == 2

这篇关于如何在 Groovy 中按标签名称查找所有 XML 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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