如何找到具有Groovy中具有特定值的节点的文本?
-
14-12-2019 - |
题
我正在使用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
在简单地使用深度时,我可以让它工作。所以:
properties[ "finalValue" ] = page.depthFirst().find {
it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};
. 其他提示
您可以使用GPAPE符号,并首先检查“@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
. 不隶属于 StackOverflow