XPath 仅返回包含文本的元素,而不返回其父元素 [英] XPath to return only elements containing the text, and not its parents

查看:27
本文介绍了XPath 仅返回包含文本的元素,而不返回其父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个xml中,我要匹配,包含'match'的元素(random2元素)

In this xml, I want to match, the element containing 'match' (random2 element)

<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)

这将返回 random2、random1 和 root...我只想得到random2"

this returns random2, random1 and root... I would like to get only "random2"

有什么想法吗?

推荐答案

您是否要查找包含匹配"或相等的元素匹配"?

Do you want to find elements that contain "match", or that equal "match"?

这将查找具有等于匹配"的文本节点的元素(由于 random2 中的前导和尾随空格,不匹配任何元素):

This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):

//*[text()='match']

<小时>

删除前导和尾随空格(匹配random2)后,这将找到所有文本节点等于匹配"的元素:


This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):

//*[normalize-space(text())='match']

<小时>

这将查找文本节点值中包含match"的所有元素(匹配 random2random3):

//*[contains(text(),'match')]

<小时>

XPATH 2.0 解决方案使用 matches() 函数和正则表达式模式,该模式查找包含匹配"并从字符串开头的文本节点(即 ^) 或词边界(即 \W)并以字符串结尾(即 $)或词边界终止.第三个参数 i 评估不区分大小写的正则表达式模式.(匹配random2)


This XPATH 2.0 solution 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 i evaluates the regex pattern case-insensitive. (matches random2)

//*[matches(text(),'(^|\W)match($|\W)','i')]

这篇关于XPath 仅返回包含文本的元素,而不返回其父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆