How to check if an element exists in the XML using XPath?

JavaXmlXpathSaxon

Java Problem Overview


Below is my element hierarchy. How to check (using XPath) that AttachedXml element is present under CreditReport of Primary Consumer

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

Java Solutions


Solution 1 - Java

Use the boolean() XPath function

> The boolean function converts its > argument to a boolean as follows: > > * a number is true if and only if > it is neither positive or negative > zero nor NaN > > * a node-set is true if and only if > it is non-empty > > * a string is true if and only if > its length is non-zero > > * an object of a type other than > the four basic types is converted to a > boolean in a way that is dependent on > that type

If there is an AttachedXml in the CreditReport of primary Consumer, then it will return true().

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

Solution 2 - Java

The Saxon documentation, though a little unclear, seems to suggest that the JAXP XPath API will return false when evaluating an XPath expression if no matching nodes are found.

This IBM article mentions a return value of null when no nodes are matched.

You might need to play around with the return types a bit based on this API, but the basic idea is that you just run a normal XPath and check whether the result is a node / false / null / etc.

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
}

Solution 3 - Java

Use:

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

Solution 4 - Java

Normally when you try to select a node using xpath your xpath-engine will return null or equivalent if the node doesn't exists.

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

If your using xsl check out this question for an answer:

https://stackoverflow.com/questions/767851/xpath-find-if-node-exists

Solution 5 - Java

take look at my example

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

now how to check if creative common is exist

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

hope this help you

Solution 6 - Java

If boolean() is not available (the tool I'm using does not) one way to achieve it is:

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

In this case, within the /OPTION, one of the options is the selected one. The "selected" does not have a value... it just exists, while the other OPTION do not have "selected". This achieves the objective.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAravind YarramView Question on Stackoverflow
Solution 1 - JavaMads HansenView Answer on Stackoverflow
Solution 2 - JavaJon GauthierView Answer on Stackoverflow
Solution 3 - JavaDimitre NovatchevView Answer on Stackoverflow
Solution 4 - JavaSimon Stender BoisenView Answer on Stackoverflow
Solution 5 - JavaBasheer AL-MOMANIView Answer on Stackoverflow
Solution 6 - Javax_kiterView Answer on Stackoverflow