xml XPath 仅返回包含文本的元素,而不返回其父元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2994198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XPath to return only elements containing the text, and not its parents
提问by julian
In this xml, I want to match, the element containing 'match' (random2 element)
在这个 xml 中,我想匹配包含 'match' 的元素(random2 元素)
<root>
<random1>
<random2>match</random2>
<random3>nomatch</random3>
</random1>
</root>
ok, so far I have:
好的,到目前为止我有:
//[re:test(.,'match','i')] (with re in the proper namespace)
this returns random2, random1 and root... I would like to get only "random2"
这将返回 random2、random1 和 root...我只想得到“random2”
any ideas?
有任何想法吗?
回答by Mads Hansen
Do you want to find elements that contain"match", or that equal"match"?
您要查找包含“匹配”或等于“匹配”的元素吗?
This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):
这将找到具有等于 'match' 的文本节点的元素(由于 中的前导和尾随空格,不匹配任何元素random2):
//*[text()='match']
This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):
在删除前导和尾随空格(匹配random2)后,这将找到具有等于“匹配”的文本节点的所有元素:
//*[normalize-space(text())='match']
This will find all elements that contain 'match' in the text node value (matches random2and random3):
这将找到在文本节点值(匹配random2和random3)中包含“匹配”的所有元素:
//*[contains(text(),'match')]
This XPATH 2.0solution uses the matches()function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^) or a word boundary (i.e. \W) and terminated by the end of the string (i.e. $) or a word boundary. The third parameter ievaluates the regex pattern case-insensitive. (matches random2)
此XPATH 2.0解决方案使用该matches()函数和正则表达式模式来查找包含“匹配”并从字符串开头(即^)或单词边界(即\W)并以字符串结尾(即$)结尾的文本节点或字边界。第三个参数i评估不区分大小写的正则表达式模式。(匹配random2)
//*[matches(text(),'(^|\W)match($|\W)','i')]
回答by Gregtheitroade
Try
尝试
//re:*[. ='match']

