facetostool
facetostool

Reputation: 723

Xpath first text before needed tag

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.

Upvotes: 3

Views: 300

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

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

Upvotes: 4

Related Questions