Get the non-empty element using XPATH

2020-02-26 03:56发布

问题:

I have the following XML

<?xml version = "1.0" encoding = "UTF-8"?>
<root>
  <group>
    <p1></p1>
  </group>
  <group>
    <p1>value1</p1>
  </group>
  <group>
    <p1></p1>
  </group>
</root>

is it possible to get the last the node with value? in this case get the value of the second group/p1.

回答1:

How about something like /root/group/p1[text() and not(../following-sibling::group/p1/text())]

In other words: get the p1 elements that have text and whose group parents are not followed by group nodes that have non-empty p1 elements.



回答2:

This xpath should work as well:

//group/p1[string-length(text()) > 0] 


回答3:

You may also use [not(node())] Selector. Example: //group/p1[not(node())]



标签: xpath