0

I want to check if a certain xml tag exists in a file, and do something if it does and something else if it doesn't exist.

I am iterating through the file like this:

def root = new XmlSlurper().parseText(xml)
        root.node.each { node ->
          println "found node"
        }

So how do I make some kind of "else" bracket which executes if the node doesn't exist?

(The XML file is big and consists of many different tags. I want to know if a specific tag exists. In this example the 'node' tag)

One way of doing the same would be:

boolean exists = false
def root = new XmlSlurper().parseText(xml)
    root.node.each { node ->
      exists = true
      println "found node"
    }

if(exists) {
  // do something
}

Can it be done more elegant?

Jonas Praem
  • 2,296
  • 5
  • 32
  • 53
  • You mean node / tag exists? what is your use case? would you mind provide sample data that you are talking about? – Rao May 10 '17 at 12:18
  • 1
    Possible duplicate of [How can I check for the existence of an element with Groovy's XmlSlurper?](http://stackoverflow.com/questions/480431/how-can-i-check-for-the-existence-of-an-element-with-groovys-xmlslurper) – Rao May 10 '17 at 12:24

1 Answers1

1

You can use breadthFirst().any { } to search the whole xml:

def hasNodeTag(xml) {
    new XmlSlurper()
        .parseText(xml)
        .breadthFirst()
        .any { it.name() == "node" }
}

def xml = '''
<html>
    <head></head>
    <body>
        <node></node>
    </body>
</html>
'''

if (hasNodeTag(xml) ) {
    println "xml has 'node' tag"
}
else {
    println "xml doesn't have 'node' tag"
}
Will
  • 14,348
  • 1
  • 42
  • 44