Mike Donovan
Mike Donovan

Reputation: 21

Xpath query to find nodes whose descendants contain particular text

Doing some PHP/Xpath coding for some scraping, and I want to know an XPath expression to select nodes which have a parent whose sibling, somewhere in their descendant tree, contain a node with a particular text value.

Say the node is something like span[@ng="league"] and the text value somewhere in a descendant is 'SKT', I believe it should in some way include contains(text(), 'SKT'), but I'm not quite sure on the rest. TIA.

I've tried to create a diagram of the situation here

|
+[parent]
|    |
|   [the node I want]
|     
+[sibling of "parent" node seen above]
|   |
|   *
|   |
|   +---[specific text, found with previous xpath query]
|
etc

Upvotes: 2

Views: 2784

Answers (2)

splash58
splash58

Reputation: 26143

If your xml is something as

<parent>
  <span ng="league">The node you want </span>
</parent>
<any>
    <any2>
       <any3>SKT</any3>
   </any2>
</any>

you can use such xpath

//span[@ng="league"][../following-sibling::*[contains(., "SKT")]]

Upvotes: 1

har07
har07

Reputation: 89285

The following XPath will return span[@ng="league"] elements where there is at least one text node anywhere within the span that contain substring 'SKT':

//span[@ng="league" and .//text()[contains(., 'SKT')]]

If this doesn't work then you need to be more specific i.e post minimal HTML/XML example (formatted text, not image) where the XPath above doesn't return the desired output

Upvotes: 3

Related Questions