T...">

Xquery - getting the number of these elements inside a single parent that are not empty

Please consider the following XML -

<div id="test"> <p> Text sihdfaif</p> <p /> <p> Text sihdfaif</p> <p /> <p> Text sihdfaif</p> <p> Text sihdfaif</p> <p> Text sihdfaif</p> </div> 

Now I want to get the number p of elements that contain some text .. in this case it is value = 5 (there are two 'p' elements that are empty)

This is the XQuery I came across -

  let $claims_main := $doc//div[@id="test"] let $claims := $doc//div[@id="test"]/p let $n := count($claims) where $claims_main/p != '' return $n 

However, the result that I get from the above is 7, that is, including the empty p elements.

An alternative that I was thinking about is to use a for loop for all p elements, but in this case, how can I get the total number of loop elements? If I use the account in this case, then I just get [1,1,1,1,1,1] - i.e. counting each element of p (since in the for loop, the count will be for each of the elements of p, not the div itself) ...

+4
source share
2 answers

Since the question is asked specifically for p elements that contain some text " ,, here's how to get the number of exactly such p elements:

 count(/*/div/p[string(.)]) 

This results in the number of all p elements with a non-empty string value, which are children of the div , which are children of the top element of the XML document.

In addition, if "non-empty" also means that there is a string value for white space only :

 count(/*/div/p[normalize-space(.)]) 
+7
source

Try the following:

 count($doc//div[@id='test']/p[node()]) 

the second predicate [node()] selects only elements containing child nodes, it is equivalent to [./node()] .

+1
source

Source: https://habr.com/ru/post/1434453/


All Articles