Search code examples
xpath

How to select the text node just before the closing tag, but only when there is such a text node


I would like to extract the text nodes that are just before the closing tag of the a elements. For example, with this sample XML:

<root>
  <a/>
  <a>1</a>
  <a>2<b/>3</a>
  <a>4<b/></a>
  <a><b/>5<c/></a>
</root>

The expected result would the sequence ( 1, 3 )

The expression //a/text()[last()] isn't enough, as it returns ( 1, 3, 4, 5 ), and my problem is that I don't see how to add the constraint: "just before the closing tag of a".


Solution

  • Try this

    //a/text()[not(following-sibling::node())]
    

    It selects text nodes directly before the closing </a> tag.

    For your example, it returns 1, 3.