Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML xpath, get the parent element till a specific element

I'm looking for the right xpath syntax to get a specific parent of an element. Example:

root    |- div    |     |    |     |----??? ---|    |     |           |-a [class=1]    |     |                      |- text[ A TEXT I DON'T WANT]    |     |    |     |    |     |    |     |-text[THE TEXT]    |    |-div     |    |-text[THE TEXT I DON'T WANT]    |    |-div     |    |-text[THE TEXT I DON'T WANT] 

I want to get the text "THE TEXT" but the one that contains a [class=1] inside the same div. Something like this:

//div//a[@class=1]/text[contains(.,'A TEXT')]/parent::*/parent::*.... <till div element>  /text 
like image 732
Nir Bentzy Avatar asked May 29 '11 11:05

Nir Bentzy


People also ask

How do you get the parent of an element in XPath?

A Parent of a context node is selected Flat element. A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.

How do I traverse back to parent in XPath?

IN the XPath we can traverse backward using the double dots(..). We can traverse backward as many levels as we want like ../../… For example, if we want to find the parent of any child div selector then we can use it as.

What is difference between ancestor and parent in XPath?

The difference between parent:: and ancestor:: axis is conveyed by their names: A parent is the immediately direct ancestor. So, yes /a/b/c/d/ancestor::*[1] would be the same as /a/b/c/d/parent::* .


2 Answers

Given the XML

 <?xml version="1.0"?> <root>     <foo id="id1">         <foo id="i2">             <baz/>         </foo>     </foo> </root>

You can find the nearest ancestor foo element from baz using the XPath expression:

//baz/ancestor::foo[1]

Which will select the foo element node of id "i2".

So in your example (if I understand right) once you have got the "a" element you want, you can get "back up" the tree to the nearest ancestor div by appending "/ancestor::div[1]" to your expression.

like image 187
alexbrn Avatar answered Nov 12 '22 20:11

alexbrn


Use:

/root/div[.//a[@class='1']]/text() 

This selects any text node that is a child of any a element that has a class attribute with value '1' and that (the a element) is a descendent of any div element that is a child of the top element named root.

like image 40
Dimitre Novatchev Avatar answered Nov 12 '22 21:11

Dimitre Novatchev