如何使用XPath判断元素是否存在且为非空? [英] How to tell using XPath if an element is present and non empty?

查看:1623
本文介绍了如何使用XPath判断元素是否存在且为非空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这一行上有一个输入XML:

I have an input XML something on this line:

<Holding id="12">
    <Policy>
        <HoldingForm tc="1">Individual</HoldingForm>
        <PolNumber>848433</PolNumber>
        <LineOfBusiness tc="1">Life</LineOfBusiness>
        <CarrierCode>67644</CarrierCode>
    </Policy>
</Holding>

我对这个XML的操作取决于<PolNumber>(它是模式中的可选元素)是否具有值.我正在使用Mule 3.3 xpath评估程序执行此操作,而我的XPath表达式看起来像这样:

My manipulation on this XML depends on if <PolNumber> (its an optional element in schema) has a value or not. I'm using Mule 3.3 xpath evaluator to do this and my XPath expression looks this:

<expression-filter expression="#[xpath('//acord:Holding/acord:Policy/acord:PolNumber').text != empty]"/> 

只要存在<PolNumber>元素或<PolNumber/>为空元素,此方法就可以正常工作.但是,如果不存在<PolNumber>,则上面的表达式将引发异常.

This works fine as long as <PolNumber> element is present or <PolNumber/> is empty element. But if <PolNumber> is absent, above expression throws exception.

我尝试使用 XPath布尔函数,但它为true返回<PolNumber/>.有没有更好的方法来检查元素是否存在且为非空?

I tried using XPath boolean function but it returns true for <PolNumber/>. Is there a better way of checking if an element is present and non-empty?

这是我的m子配置中名称空间管理器的配置

This is the configuration of namespace manager in my mule config

<xm:namespace-manager includeConfigNamespaces="true">
    <xm:namespace prefix="acord" uri="http://ACORD.org/Standards/Life/2" />
    <xm:namespace prefix="soap" uri="http://schemas.xmlsoap.org/soap/encoding/" />
</xm:namespace-manager>

推荐答案

使用:

boolean(//acord:Holding/acord:Policy/acord:PolNumber/text()[1])

如果//acord:Holding/acord:Policy/acord:PolNumber有第一个文本节点子代,则生成true(),否则生成false().

this produces true() if //acord:Holding/acord:Policy/acord:PolNumber has a first text-node child, and false() otherwise.

注意:这比对所有文本节点子代进行计数(仅将计数与0进行比较)更为有效.

Do note: This is more efficient than counting all text-node children just to compare the count with 0.

这篇关于如何使用XPath判断元素是否存在且为非空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆