Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath first text before needed tag

Tags:

html

xpath

I have some HTML code:

<dl>
    <div>
       <div>foo</div>
    <div>
    "I need getting only this text"
    <dd>
       <div>foo</div>
       <div>foo</div>
    </dd>
    <div>
        <div>foo</div>
    <div>
    "I need getting only this text"
    <dd>
        <div>foo</div>
        <div>foo</div>
    </dd>
</dl>

So I need getting only first text before a required tag(not "foo"). I tried syntax like

//text()[(preceding::dd)][some integer]

or

//text()[(preceding::dd)][last()]

but it's all now working for me, because count of div with "foo" - undefined. I need some xpath, like //dl/text() but returns direct ancestor of 'dl', no some level deeper.

like image 692
facetostool Avatar asked Jun 27 '26 02:06

facetostool


1 Answers

So I need getting only first text before a required tag

How about this:

//dd/preceding-sibling::text()[1]

i.e. find the dd tags and then for each of those take the nearest preceding sibling text node. Given your example this would return a set of two text nodes, each of which contains the text

'
    "I need getting only this text"
    '

(without the single quotes, i.e. newline, four spaces, double quote, I need getting only this text, double quote, newline, four spaces).

like image 174
Ian Roberts Avatar answered Jun 28 '26 21:06

Ian Roberts



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!