如何使用XPath选择末尾空节点?
How to Select Trailing Empty Nodes Under
<bar> To target only the empty <node> elements that come after the last non-empty <node> in your <bar> container (ignoring earlier empty nodes), you can use these XPath expressions tailored to your definition of "empty" (no text content, including descendants):
Key XPath Expressions
1. Select all trailing empty nodes
This expression picks every empty <node> where there are no non-empty <node> elements following it:
//bar/node[string-length(.) = 0 and not(following-sibling::node[string-length(.) > 0])]
2. Alternative: Target after the last non-empty node
First, locate the last non-empty <node>, then select all empty siblings that come after it:
//bar/node[string-length(.) > 0][last()]/following-sibling::node[string-length(.) = 0]
Breakdown of the Logic
Let’s map this to your example:
blah blah blah blah blah blah
string-length(.) = 0: Checks if the node (and all its descendants) have no text content. This includes both empty<node></node>and nested empty nodes like<node><node></node></node>.not(following-sibling::node[string-length(.) > 0]): Ensures there are no non-empty<node>elements after the current node—so it’s part of the trailing empty sequence.
Adjusting for Strictly Empty Nodes (No Child Nodes)
If you only want nodes with no child elements or text (i.e., exclude <node><node></node></node>), modify the condition to check for zero child nodes and empty text:
//bar/node[count(node()) = 0 and string-length(text()) = 0 and not(following-sibling::node[string-length(.) > 0])]
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

