Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XPath count() with contains()

Tags:

xml

xpath

I am working with the following (suboptimal) XML:

<a>
  <b>
    <c>X:1 Y:0</c>
    <c>X:1 Y:0</c>
    <c>X:2 Y:0</c>
  </b>
  <b>
    <c>X:1 Y:0</c>
    <c>X:2 Y:0</c>
  </b>
</a>

I am trying to use XPath to count the number of <c> nodes whose contents contain X:1:

count(contains(/a/b/c, 'X:1'))

However, this returns an error rather than returning the expected count of 3.

What am I doing wrong?

like image 263
gjb Avatar asked Dec 15 '11 00:12

gjb


2 Answers

That isn't how you use contains(). Try

count(/a/b/c[contains(., 'X:1')])
like image 61
Phil Avatar answered Oct 18 '22 15:10

Phil


Probably a little bit more efficient (if the property exhibited in the provided XML document isn't accidental):

count(/a/b/c[starts-with(., 'X:1')])
like image 30
Dimitre Novatchev Avatar answered Oct 18 '22 16:10

Dimitre Novatchev