Search code examples
grailsgroovyclosuresxmlslurperhtmlcleaner

How would I find the text of a node that has a specific value for an attribute in groovy?


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?


Solution

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