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

150,476

Solution 1

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

Use:

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

Solution 3

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 4

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:

xpath find if node exists

Share:
150,476
Aravind Yarram
Author by

Aravind Yarram

Winner of Hackathon @ Kafka Summit 2016. 2nd Place, Neo4j Graph Gist Winter Challenge 2014. Data informed over data driven. Datasets over algorithms. Delivery over ceremonies. Metrics over anecdotes. Hypothesis over intuition. Evidence over experience. Trade-offs over trends. https://www.linkedin.com/in/aravindyarram

Updated on January 21, 2022

Comments

  • Aravind Yarram
    Aravind Yarram over 2 years

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