GPathResult ..存在或不存在节点

use*_*230 6 java xml groovy xpath gpath

我的GPathResult可以使用3种方式之一的名称节点

1)名称节点存在并且具有值ex:John

2)名称节点存在,但没有值.

3)根本没有名称节点.

在Groovy代码中,我如何使用我的Gpathresult区分上述3个案例.我是否使用像gPathResult这样的东西.value()!= null?

Pesudo代码:

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
}
Run Code Online (Sandbox Code Playgroud)

小智 -1

测试 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"
    }
}
Run Code Online (Sandbox Code Playgroud)

(该gpath[it]符号是因为变量替换,如果您查找特定元素,例如bthen 您可以使用gpath.b