user2513552
user2513552

Reputation: 33

how to do element exist check using XMLParser()

I'm not very good at groovy and sorry in advance it might be very basic. I've written all my code using XMlParser() class so just cant go back to other available classes ( e.g XMLSlurper).

def data ="""<?xml version="1.0" encoding="UTF-8"?>
           <foo>
           </bar>
           </foo>"""

i need to check if element exists. I have used various ways example

def xml= new XmlParser().parseText(data);

if(xml.foo.bar.isEmpty())
def value = xml.foo.bar.text()

Also tried

if(xml.foo.bar == null)
def value = xml.foo.bar.text()

Also tried

if(xml.foo.bar.size() == 0)  ==> this works in XMLSlurper
def value = xml.foo.bar.text()

but nothing seems to be working. Can anyone help please? I could not find any good documentation/code example as well for XMLParser() class

Upvotes: 0

Views: 993

Answers (1)

daggett
daggett

Reputation: 28564

after paring the xml variable already references root element foo

so, your accessor should be

if(xml.bar)...

the code could look like this

def data ="""<?xml version="1.0" encoding="UTF-8"?>
           <foo>
           <bar>123</bar>
           </foo>"""

def xml= new XmlParser().parseText(data);

assert xml.bar
def value = xml.bar.text()

Upvotes: 1

Related Questions