58

下面是我的元素层次结构。如何检查(使用 XPath)AttachedXml元素是否存在于主要消费者的CreditReport

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

6 回答 6

91

使用boolean()XPath 函数

布尔函数将其参数转换为布尔值,如下所示:

  • 一个数为真当且仅当它既不是正零也不是负零也不是 NaN

  • 一个节点集当且仅当它非空时为真

  • 字符串为真当且仅当其长度非零

  • 四种基本类型以外的类型的对象以依赖于该类型的方式转换为布尔值

如果primary ConsumerCreditReport中有AttachedXml,则返回。 true()

boolean(/mc:Consumers
          /mc:Consumer[@subjectIdentifier='Primary']
            //mc:CreditReport/mc:AttachedXml)
于 2011-04-17T00:04:09.187 回答
6

使用

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )
于 2011-04-17T00:12:17.687 回答
5

Saxon 文档虽然有点不清楚,但似乎暗示如果没有找到匹配的节点,则在评估 XPath 表达式时,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
}
于 2011-04-16T22:46:56.310 回答
4

通常,当您尝试使用 xpath 选择节点时,如果该节点不存在,您的 xpath-engine 将返回 null 或等效项。

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

如果您使用 xsl,请查看此问题以获得答案:

xpath 查找节点是否存在

于 2011-04-16T22:15:48.953 回答
0

看看我的例子

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

现在如何检查是否creative common存在

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

希望这对你有帮助

于 2017-03-14T11:39:30.777 回答
-1

如果 boolean() 不可用(我使用的工具不可用),实现它的一种方法是:

//SELECT[@id='xpto']/OPTION[not(not(@selected))]

在这种情况下,在 /OPTION 中,选项之一是选定的选项。“选定”没有值......它只是存在,而其他选项没有“选定”。这样就达到了目的。

于 2013-06-11T00:38:35.370 回答