XPATH select parent node by type containing text

Viewed 92

I need to select all n nodes by containing the text "text to match"

<n>
  <n>
    <s>text to match</s>
  </n>
  <n>
    <s>ignore</s>
  </n>
  <n>
    <s>text to match</s>
  </n>
  <n>
    text to match
  </n>
</n>

I tried *[contains(string(), "text to match")] but that selects the outer-most n as well I would like to get only the nearest possibly n. Any hints? TIA!

2 Answers

Since text to match can appear in nodes with different tag name and you are looking for the nearest parent n node, I think

//*[contains(text(), "text to match")]/parent::n

would make what you are looking for here

Try this one to fetch required n nodes:

//n[normalize-space()='text to match']

or

//n[contains(., 'text to match') and not(descendant::n)]
Related