如何在groovy中找到具有特定属性值的节点文本?

时间:2012-03-14 20:30:43

标签: grails groovy closures xmlslurper htmlcleaner

我正在使用XMLSlurper。我的代码在下面(但不起作用)。问题是当它遇到没有属性“id”的节点时它会失败。我如何解释这个?

//Parse XML
def page = new XmlSlurper(false,false).parseText(xml)

//Now save the value of the proper node to a property (this fails)
properties[ "finalValue" ] = page.find {
    it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};

我只需要考虑没有“id”属性的节点,这样就不会失败。我该怎么做?

2 个答案:

答案 0 :(得分:1)

您也可以使用GPath表示法,并检查“@id”是否为空。

以下代码段找到最后一个元素(因为id属性为“B”,值也是“bizz”,它打印出“bizz”和“B”)。

def xml = new XmlSlurper().parseText("<foo><bar>bizz</bar><bar id='A'>bazz</bar><bar id='B'>bizz</bar></foo>")
def x =  xml.children().find{!it.@id.isEmpty() && it.text()=="bizz"}
println x
println x.@id

答案 1 :(得分:0)

当我只使用depthFirst时,显然我可以让它工作。所以:

properties[ "finalValue" ] = page.depthFirst().find {
    it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};