Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first ancestor with Xpath

Tags:

php

xpath

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

like image 568
guillaume Avatar asked Oct 11 '12 21:10

guillaume


1 Answers

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".

like image 122
Dimitre Novatchev Avatar answered Oct 17 '22 14:10

Dimitre Novatchev