GPathResult ..presence or absence of a node
Asked Answered
M

2

6

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
}
Maintop answered 11/4, 2013 at 20:25 Comment(0)
P
4

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"
    }
}
Pulliam answered 27/8, 2015 at 12:14 Comment(0)
S
-1

Test if gpath result is null to check presence, and use .text() method for the element value (empty string if no value). Here's an example:

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

(the gpath[it] notation is because of the variable replacement, if you look for a specific element such as b then you can use gpath.b)

Shingle answered 17/4, 2013 at 16:5 Comment(2)
XmlParser does not return a GPathResult but a Node. Those two behave differently in the scope of this question, as your else path will NEVER be triggered.Pulliam
Vampire is correct, here is a document with some info about XmlParser and Node as opposed to XmlSlurper and GPathResult.Paragrapher

© 2022 - 2024 — McMap. All rights reserved.