Search code examples
xmlxpathxpath-2.0mismatchxpath-1.0

Xpath find a node value matches in another node partially


I have this XML:

<ref>
  <label>MCLaren, 1996</label>
  <year>1997</year>
</ref>
<ref>
  <label>Dhanvanth, 2016</label>
  <year>2016</year>
</ref>
<ref>
  <label>Darwin2 2001</label>
  <year>1997</year>
</ref>

I want to check year value "1997" against above label value "MCLaren, 1996" within respective tag if year value mismatch with label need to show, answer expected in XPath

I have tried the below code:

/ref[descendant::label != descendant::year[contains(text(),'')]]

Solution

  • I'm not sure, if I understood what you want correctly, but the following XPath:

    /root/ref[not(contains(descendant::label/text(), descendant::year/text()))]
    

    returns all refs, where the year text is not contained in the label text

    Output

    <ref>
      <label>MCLaren, 1996</label>
      <year>1997</year>
    </ref>
    <ref>
      <label>Darwin2 2001</label>
      <year>1997</year>
    </ref>