Search code examples
xmlxpathnodeslimitpredicate

Xpath, why does it matches both?


<root>
  <a>
    <b>
      <ba>
        <baa>RM</baa>
        <bab>*DB:ZA:4</bab>
      </ba>
    </b>
    <c>
      <ca>M</ca>
      <cb>1</cb>
    </c>
  </a>
  <a>
    <b>
      <ba>
        <baa>RM</baa>
        <bab>*DB:ZA:4</bab>
      </ba>
    </b>
    <c>
      <ca>S</ca>
      <cb>1</cb>
    </c>
  </a>
</root>

And the following xPath: //a[//bab/text() = '*DB:ZA:4' and //ca/text() = 'S']

This returns both 'a' nodes. But I only want the one with ca='S'

I can achieve that by using .//ca/text() = 'S'. But I don't know why. Can someone epxlain? Does the xpath loses the context where it is after the 'and' ?

I used this XPath-Tester: http://videlibri.sourceforge.net/cgi-bin/xidelcgi


Solution

  • Because locator like element[//anotherElement] - returns element, but ensures that somewhere anotherElement is present.

    And locator element[.//anotherElement] - returns element element for which there's descendant anotherElement.

    Adding dot, in that case, changes search from absolute to relative path.