xml 如何使用 Groovy 的 XmlSlurper 检查元素的存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/480431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:19:25  来源:igfitidea点击:

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

xmlgroovyxmlslurper

提问by Josh Brown

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

我正在尝试使用 Groovy 的 XmlSlurper 确定 XML 元素是否存在。有没有办法做到这一点?例如:

<foo>
  <bar/>
</foo>

How do I check whether the bar element exists?

如何检查 bar 元素是否存在?

回答by Ted Naleid

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.NodeChildrenobject. Basically a collection of nodes meeting the criteria that you asked for.

API 有点乱,但我认为有几个更好的方法来寻找孩子。当您要求“xml.bar”(存在)或“xml.quux”(不存在)时,您得到的是groovy.util.slurpersupport.NodeChildren对象。基本上是满足您要求的标准的节点集合。

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

查看特定节点是否存在的一种方法是检查 NodeChildren 的大小是否为预期大小:

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:

另一种方法是使用 find 方法并查看返回的节点名称(不幸的是总是返回某些内容)是否是您期望的名称:

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())

回答by Josh Brown

The isEmpty method on GPathResult works.

GPathResult 上的 isEmpty 方法有效。

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

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

这让我很困扰,因为 bar 元素空的 - 它没有主体。但我想 GPathResult 不是空的,所以也许这是有道理的。