如何在GPath中按属性值查找元素?

时间:2011-08-11 04:28:18

标签: java xpath groovy gpath

GPath中此XPath //div[@id='foo']的替代方法是什么?一般来说,我可以在哪里找到这份文件?

4 个答案:

答案 0 :(得分:28)

以下是相应的代码段:

def node = new XmlSlurper().parseText(...)
def foo = node.depthFirst().findAll { it.name() == 'div' && it.@id == 'foo'}

您可能想要阅读的其他一些链接:

答案 1 :(得分:8)

上一张海报为您提供了所需要的一切:假设您的文件已被插入xml,您想要

def foo = xml.path.to.div.find{it.@id == 'foo'}

找到一个结果。或findAll查找所有结果。

答案 2 :(得分:2)

要模仿表达式[div [@ id ='foo'],你可以用GPath做的最接近的事情是:

def xml = new XmlParser().parseText(text)
xml.'**'.div.findAll { it.@id=="foo" }

'**'与XPath中的'//'几乎相同。

xml.'**'.div

将在任何级别产生div类型的所有节点。

稍后使用给定闭包的findAll()进行过滤,您将获得与XPath案例中一样的节点列表

答案 3 :(得分:1)

你需要的是:

def root = new XmlSlurper().parseText(<locOfXmlFileYouAreParsing>.toURL().text)

def foundNode = root.'**'.find{ it.@id == "foo" }

它的双*可以让你在不知道路径的情况下找到它。至少我就是这样做的。

相关问题