Reputation: 1678
I want to use XPath to get the first parent ancestor. I want to parse a code like this :
<div>
<span class="city">City 1</span>
<div class="annonce">
<span class="item">Item1</span>
</div>
</div>
<div>
<div class="annonce">
<span class="item">Item2</span>
</div>
</div>
<div>
<span class="city">City 2</span>
<div class="annonce">
<span class="item">Item3</span>
</div>
</div>
<div>
<div class="annonce">
<span class="item">Item4</span>
</div>
</div>
And with XPath I want to get the first parent city. For example, for Item1, Item2 I want to have City 1 And for Item3, Item4 I want City 2
It's possible to do it ? P.S : I can't edit the source code.
Thanks
Upvotes: 6
Views: 13188
Reputation: 243489
I want to use XPath to get the first parent ancestor.
This terminology is incorrect and misleading. "parent ancestor" isn't meaningful, because a parent is always an ancestor.
Also. the elements you want to select aren't parents or ancestors to any span[@class='item']
element.
Finally, the provided text isn't a well-formed XML document. In a well-formed XML document there is exactly one top element.
This said,
Use:
preceding::span[@class='city'][1]
this selects the first preceding span
element of the context (current) node, whose class
attribute's string value is the string "city"
.
Upvotes: 10