Search code examples
xmlcountxquerynodesexist-db

XQuery issue when counting empty nodes and nodes that don't have a specific text (ne)


I want to count all the r elements that don't have the text "unspecified" within them.

<!-- test.xml -->
<e>
<r/>
<r/>
<r>hi</r>
<r>there</r>
<r>you</r>
<r>all</r>
<r>unspecified</r>
<r>unspecified</r>
</e>

I am employing the following XQuery:

let $r_nodes := count(doc('test.xml')//r[text() ne 'unspecified'])
return
  $r_nodes

The $r_nodes variable gives me 4 not 6 as I was expecting,


Solution

  • You can use string() or even more compact, . instead of text() to correctly consider element that doesn't contain any text node :

    let $r_nodes := count(doc('test.xml')//r[. ne 'unspecified'])
    return
      $r_nodes