Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell using XPath if an element is present and non empty?

Tags:

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> 

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]"/>  

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

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?

EDIT:

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> 
like image 543
Charu Khurana Avatar asked Apr 09 '13 18:04

Charu Khurana


People also ask

What does /* mean in XPath?

/* selects the root element, regardless of name. ./* or * selects all child elements of the context node, regardless of name.

How do I check if XPath exists?

Use the fn:nilled XPath function to test whether the value of an input element has the xsi:nil attribute set. Use the fn:exists XPath function to test whether the value of an input element is present. Note: An XML element that has the xsi:nil attribute set is considered to be present.

What does node () do in XPath?

node() matches any node (the least specific node test of them all) text() matches text nodes only. comment() matches comment nodes. * matches any element node.

Can we use and with Contains in XPath?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]


1 Answers

Use:

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

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

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

like image 118
Dimitre Novatchev Avatar answered Sep 20 '22 17:09

Dimitre Novatchev