Java中XPath的string-length函数不生效,元素匹配异常求助
Fixing Your XPath Selection Issue
Hey there! Let's figure out why your XPath isn't picking up the right element and get it sorted.
The Problem with Your Original XPath
Your current query uses string-length(text()), and that's likely the culprit:
//*[contains(.,'About') and contains(.,'/') and (string-length(text()) < 9)]
text()in XPath only returns the first direct text node of an element. If your target element has child elements (even invisible ones like<span>) or multiple separate text nodes,text()won't capture the full visible text you're targeting.contains(., 'About')andcontains(., '/')check the entire element's content (including child nodes), but the length check is only against a partial text snippet—so these two parts are out of sync.
The Corrected XPath
To reliably target elements with the full text containing "About", "/", and a total length (after cleaning up whitespace) under 9, use this:
//*[ contains(normalize-space(string(.)), 'About') and contains(normalize-space(string(.)), '/') and string-length(normalize-space(string(.))) < 9 ]
What Each Part Does
string(.): Grabs the entire combined text content of the element (including all child nodes) as a single string—no more missing parts from text nodes.normalize-space(): Strips leading/trailing whitespace and collapses multiple spaces/newlines into one, so extra whitespace doesn't throw off your length check or contains matches.- The length check now uses the same full cleaned string as the contains checks, keeping everything consistent.
Quick Note
If you specifically only want to consider the direct text of the element (excluding child elements), you can use concat(text(), '') to merge all direct text nodes instead of string(.), but string(.) is almost always the safer bet for matching visible text.
内容的提问来源于stack exchange,提问作者gigimooshi
相关产品推荐
相关产品推荐

