如何使用XPath检查XML中的元素是否存在?

62

以下是我的元素层次结构。如何使用XPath检查PrimaryConsumer下的CreditReport中是否存在AttachedXml元素。

<Consumers xmlns="http://xml.mycompany.com/XMLSchema">
       <Consumer subjectIdentifier="Primary">
          <DataSources>
               <Credit>
                   <CreditReport>
                      <AttachedXml><![CDATA[ blah blah]]>

3
你使用什么语言来运行XML并解析XPath?答案取决于这个。 - Jon Gauthier
我相信SoapUI内部使用的是Java引擎(Saxon)。 - Aravind Yarram
6个回答

96

使用boolean() XPath 函数

boolean函数将其参数转换为布尔值,规则如下:

  • 如果数字既不是正零也不是负零或NaN,则为true。

  • 如果节点集非空,则为true。

  • 如果字符串长度非零,则为true。

  • 除了四种基本类型之外的其他类型的对象会以特定于该类型的方式转换为布尔值。

如果在primary ConsumerCreditReport中存在AttachedXml,那么它将返回true()

boolean(/mc:Consumers
          /mc:Consumer[@subjectIdentifier='Primary']
            //mc:CreditReport/mc:AttachedXml)

这也会返回true,如果AttachedXml不存在...我错过了什么? - Aravind Yarram
不应该返回 true(),如果它返回了 true(),那么 XPath 匹配并选择了某些内容。如果没有选择任何内容,它应该返回 false() - Mads Hansen
更糟糕的是:如果节点不存在,你将得到 false();而且,如果节点内容评估为布尔值 false,同样也会得到 false()! - Enrice

6
尽管有些不太清楚,但Saxon文档似乎表明,如果没有找到匹配的节点,则JAXP XPath API将返回false这篇IBM文章提到,当没有匹配的节点时,返回值为null
根据此API,您可能需要稍微调整返回类型,但基本思路是运行正常的XPath并检查结果是否为节点/false/null/等。
XPathFactory xpathFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile("/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml");
Object result = expr.evaluate(doc, XPathConstants.NODE);

if ( result == null ) {
    // do something
}

6

使用:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

4

通常情况下,当你尝试使用xpath选择节点时,如果该节点不存在,你的xpath引擎将返回null或等效值。

xpath: "/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml"

如果你正在使用XSL,请查看以下问题以获取答案:xpath find if node exists

-1
如果 boolean() 不可用(我使用的工具没有),实现它的一种方法是:
//SELECT[@id='xpto']/OPTION[not(not(@selected))]

在这种情况下,在 /OPTION 中,其中一个选项是被选中的。 "selected" 没有值... 它只是存在,而其他 OPTION 没有 "selected"。 这样就实现了目标。

2
这与所讨论的XML无关。 - Mark Thomas

-1

看看我的例子

<tocheading language="EN"> 
     <subj-group> 
         <subject>Editors Choice</subject> 
         <subject>creative common</subject> 
     </subj-group> 
</tocheading> 

现在如何检查是否存在 创意共用

tocheading/subj-group/subject/text() = 'creative common'

希望这能帮到你


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接