Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GPathResult ..presence or absence of a node

My GPathResult can have a name node in one of the 3 ways

1) name node is present and has a value ex: John

2) name node exists, but has no value in it.

3) No name node exists at all.

In Groovy code, how do i differenciate between the above 3 cases using my Gpathresult. Do I use something like gPathResult. value()!=null ?

Pesudo code:

if(name node is present and has a value){
do this
}

if(name node exists, but has no value in it){
do this
}

if( No name node exists at all){
do this
}
like image 581
user1717230 Avatar asked Apr 11 '13 20:04

user1717230


1 Answers

You have to test for size(). To stay with the example of Olivier, just fixed so that GPathResult is used and that it works with both, XmlSlurper and XmlParser here the code:

def xml="<a><b>yes</b><c></c></a>"
def gpath = new XmlSlurper().parse(new ByteArrayInputStream(xml.getBytes())) 
["b", "c", "d" ].each() {
    println it
    if (gpath[it].size()) {
        println "  exists"
        println gpath[it].text() ? "  has value" : "   doesn't have a value"
    } else {
        println "  does not exist"
    }
}
like image 114
Vampire Avatar answered Oct 23 '22 16:10

Vampire