search

Home  >  Q&A  >  body text

XPath locates text between two tags

I need a way to select text between two tags (the first tag and the subsequent
tag):

<div>
<span>abc</span>
defg
<br>
hijkl
<br>
mnop
<span>qrs</span>
tuvw
<br>
xyz
</div>

How to select only "defg" using xpath expression?

I tried using following-sibling to find the first tag after the first
tag, but I can't find a way to select the text between them.

P粉462328904P粉462328904441 days ago487

reply all(1)I'll reply

  • P粉553428780

    P粉5534287802023-09-14 17:41:03

    Use this XML input,

    <div>
    <span>abc</span>
    defg
    <br/>
    hijkl
    <br/>
    mnop
    <span>qrs</span>
    tuvw
    <br/>
    xyz
    </div>
    

    XPath expression/div/span[1]/following-sibling::text()Returns the 5 sibling text nodes after the first element: defg, hijkl, mnop, tuvw, and xyz, each node starts and ends with a newline character.

    XPath 1.0 expression normalize-space(/div/span[1]/following-sibling::text()) will return defg, with no leading or trailing whitespace, As an argument to normalize-space(), convert it to a string by returning the string value of the node in the node set that is in document order It's the first.

    In XPath 2.0 and later, select the first item in the sequence, for example:
    normalize-space((/div/span[1]/following-sibling::text())[1]), this also works in XPath 1.0.

    reply
    0
  • Cancelreply