guillaume
guillaume

Reputation: 1678

Get the first ancestor with 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

Upvotes: 6

Views: 13188

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

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

Related Questions