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
}
user1717230
  • 443
  • 1
  • 15
  • 30

2 Answers2

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"
    }
}
Vampire
  • 35,631
  • 4
  • 76
  • 102
-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)

Olivier
  • 62
  • 2
  • 1
    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. – Vampire Aug 27 '15 at 12:18
  • Vampire is correct, [here](http://groovy-lang.org/processing-xml.html) is a document with some info about `XmlParser` and `Node` as opposed to `XmlSlurper` and `GPathResult`. – Captain Man Sep 01 '16 at 20:15