How can I check for the existence of an element with Groovy's XmlSlurper?

拟墨画扇 提交于 2020-01-01 01:09:15

问题


I'm trying to determine whether an XML element exists with Groovy's XmlSlurper. Is there a way to do this? For example:

<foo>
  <bar/>
</foo>

How do I check whether the bar element exists?


回答1:


The API is a little screwy, but I think that there are a couple of better ways to look for children. What you're getting when you ask for "xml.bar" (which exists) or "xml.quux" which doesn't, is a groovy.util.slurpersupport.NodeChildren object. Basically a collection of nodes meeting the criteria that you asked for.

One way to see if a particular node exists is to check for the size of the NodeChildren is the expected size:

def text = "<foo><bar/></foo>"
def xml = new XmlSlurper().parseText(text)
assert 1 == xml.bar.size()
assert 0 == xml.quux.size()

Another way would be to use the find method and see if the name of the node that gets returned (unfortunately something is always returned), is the one you were expecting:

def text = "<foo><bar/></foo>"
def xml = new XmlSlurper().parseText(text)
assert ("bar" == xml.children().find( {it.name() == "bar"})?.name())
assert ("quux" != xml.children().find( {it.name() == "quux"})?.name())



回答2:


The isEmpty method on GPathResult works.

def text = "<foo><bar/></foo>"
def xml = new XmlSlurper().parseText(text)
assert false == xml.bar.isEmpty()

This bothers me, because the bar element is empty - it doesn't have a body. But I suppose the GPathResult isn't empty, so maybe this makes sense.



来源:https://stackoverflow.com/questions/480431/how-can-i-check-for-the-existence-of-an-element-with-groovys-xmlslurper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!