XPath 与属性值的正则表达式匹配 [英] XPath with regex match on an attribute value
问题描述
全部 -
为了破解这个问题,我已经搜索和修改了几个小时,但我仍然遇到问题.我有以下 XML 数据:
I've searched and tinkered around for hours in an effort to crack this one, but I'm still having problems. I have the XML data below:
<game id="2009/05/02/arimlb-milmlb-1" pk="244539">
<team id="109" name="Arizona" home_team="false">
<event number="9" inning="1" description="Felipe Lopez doubles to left fielder Chris Duffy. "/>
<event number="15" inning="1" description="Augie Ojeda flies out to center fielder Mike Cameron. "/>
<event number="23" inning="1" description="Chad Tracy doubles to right fielder Joe Sanchez. "/>
<event number="52" inning="2" description="Mark Reynolds lines out to left fielder Chris Duffy. "/>
<!-- more data here -->
</team>
</game>
我正在尝试获取在 description 属性的值中包含文本doubles"的事件节点的总数.这是我到目前为止一直在尝试的方法,但无济于事(irb 抛出错误):
I'm trying to get the total number of event nodes that contain the text ' doubles ' in the value of the description attribute. This is what I've been trying so far, to no avail (irb throws an error):
"/game/team/event/@description[matches(.,' doubles ')]"
因为我只是想匹配描述属性值的片段,所以可以使用 XPath 2.0 函数匹配",对吗?如果是这样,我做错了什么?
Since I'm just trying to match a fragment of the value of the description attribute, it's possible to use the XPath 2.0 function 'matches', right? If so, what am I doing wrong?
提前感谢您的帮助!
推荐答案
我正在尝试获取总数包含文本的事件节点 'doubles ' 的值描述属性.
I'm trying to get the total number of event nodes that contain the text ' doubles ' in the value of the description attribute.
matches()
是一个标准的 XPath 2.0 函数.它在 XPath 1.0 中不可用.
您可以使用:
count(/*/*/event[contains(@description, ' doubles ')])
为了验证这一点,这里有一个小的 XSLT 转换,它只输出在提供的 XML 文档上评估上述 XPath 表达式的结果:
To verify this, here is a small XSLT transformation which just outputs the result of evaluating the above XPath expression on the provided XML document:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of select=
"count(/*/*/event[contains(@description, ' doubles ')])"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的 XML 文档时:
<game id="2009/05/02/arimlb-milmlb-1" pk="244539">
<team id="109" name="Arizona" home_team="false">
<event number="9" inning="1" description="Felipe Lopez doubles to left fielder Chris Duffy. "/>
<event number="15" inning="1" description="Augie Ojeda flies out to center fielder Mike Cameron. "/>
<event number="23" inning="1" description="Chad Tracy doubles to right fielder Joe Sanchez. "/>
<event number="52" inning="2" description="Mark Reynolds lines out to left fielder Chris Duffy. "/>
<!-- more data here -->
</team>
</game>
产生想要的正确结果:
2
这篇关于XPath 与属性值的正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!