GPathResult ..存在或不存在节点

时间:2013-04-11 20:25:45

标签: java xml xpath groovy gpath

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

1)名称节点存在且具有值 例如:约翰

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
}

2 个答案:

答案 0 :(得分:4)

您必须测试size()。 要继续使用Olivier的示例,只需修复以便GPathResult使用XmlSlurperXmlParser这两个代码:

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

答案 1 :(得分:-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"
    }
}

gpath[it]表示法是因为变量替换,如果您查找特定元素,例如b,那么您可以使用gpath.b

相关问题