GPathResult..presence or absence of a node

My GPathResult can have the name node in one of three ways.

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

2) the name node exists, but there is no value in it.  

3) There is no node name at all.

In Groovy code, how can I distinguish between the above 3 cases using my Gpathresult. Am I using 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
}
+5
source share
2 answers

You need to check size(). To stay with Olivier’s example, it’s just fixed that it is used GPathResultand that it works with both, XmlSlurperand XmlParserhere is 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"
    }
}
+4
source

, gpath null, , .text() ( , ). :

def xml="<a><b>yes</b><c></c></a>"
def gpath = new XmlParser().parse(new ByteArrayInputStream(xml.getBytes())) 
["b", "c", "d" ].each() {
    println it
    if (gpath[it]) {
        println "  exists"
        println gpath[it].text() ? "  has value" : "   doesn't have a value"
    } else {
        println "  does not exist"
    }
}

( gpath[it] - , , b, gpath.b)

-1

All Articles