Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath expression to select self, preceding and following nodes

Tags:

xpath

I'd like to select the following HTML in a document, based on the content of TARGET. I.e. if TARGET matches, select everything. However, I'm not sure where to go after: id('page')/x:div/span/a='TARGET' – How to use parent, child, and sibling expressions to get the containing div, the a preceding that div, and the two br tags following the div

<a></a>
<div>
    <br />
    <span>
        <a>TARGET</a>
        <a></a>
        <span>
            <span>
                <a></a>
            </span>
            <a></a>
            <span></span>
        </span>
        <span>
            <a></a>
        </span>
    </span>
</div>
<br />
<br />
like image 925
urschrei Avatar asked Nov 18 '25 09:11

urschrei


1 Answers

Use a single XPath like:

"//*[
     (self::a and following-sibling::*[1][self::div and span/a='TRAGET']) or
     (self::div and span/a='TARGET') or
     (self::br and preceding-sibling::*[1][self::div and span/a='TARGET']) or
     (self::br and preceding-sibling::*[2][self::div and span/a='TARGET'])
    ]"

Do note that your document is not well formed due to unclosed br tags. Moreover, I didn't include any namespace, which you can add if necessary.

like image 133
Emiliano Poggi Avatar answered Nov 21 '25 10:11

Emiliano Poggi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!