Search code examples
xmlxpathxquerydomxpathxquery-sql

XPath test for node exists and contains a number


I need a condition in XPath or XQuery to determine if a product has the node Id and if that node has a number.

<ns34:Product>
  <ns34:Id>100</ns34:Id>
</ns34:Product>
<ns34:Product>
  <ns34:Id>104</ns34:Id>
</ns34:Product>

Solution

  • Assuming that your actual XML is well-formed with a single root element...

    And that you've properly registered a namespace for the ns34 prefix...

    And that you've somehow selected the desired Product (no criteria was given in your question) and bound it to variable, $p...

    This expression will test whether $p has a ns34:Id child element:

    $p/ns34:Id
    

    And this expression will test whether it is a number:

    number($p/ns34:Id) = $p/ns34:Id
    

    And this expression will select those products that have an ns34:Id child element that is a number:

    //ns34:Product[number(ns34:Id) = ns34:Id]