Question

I'm using XMLSlurper. My code is below (but does not work). The problem is that it fails when it hits a node that does not have the attribute "id". How do I account for this?

//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"
};

I just need to account for nodes without "id" attribute so it doesn't fail. How do I do that?

Was it helpful?

Solution 2

Apprently I can get it to work when I simply use depthFirst. So:

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

OTHER TIPS

You could alternatively use the GPath notation, and check if "@id" is empty first.

The following code snippet finds the last element (since the id attribute is "B" and the value is also "bizz", it prints out "bizz" and "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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top