筛选含指定href锚点的span的XPath在xsltproc中报错,求排查
XPath在xsltproc中报错“Invalid predicate”的原因及解决方法
问题描述
我需要编写一条XPath语句,选择拥有class为versiontext且包含带有href含esv的a标签的span元素。当前使用的XPath为:
//span[.[contains(@class, 'versiontext')]/a[contains(@href, 'esv')]]
该语句在在线测试工具中正常,但本地用xsltproc运行时提示“Invalid predicate”错误。请问是XPath存在语法问题,还是xsltproc的局限性导致?
附对应HTML片段:
<span class="versiontext"><a href="/nlt/leviticus/1.htm">New Living Translation</a></span><br /> The LORD called to Moses from the Tabernacle and said to him, <span class="p"><br /><br /></span> <span class="versiontext"><a href="/esv/leviticus/1.htm">English Standard Version</a></span><br /> The LORD called Moses and spoke to him from the tent of meeting, saying, <span class="p"><br /><br /></span> <span class="versiontext"><a href="/bsb/leviticus/1.htm">Berean Standard Bible</a></span><br /> Then the LORD called to Moses and spoke to him from the Tent of Meeting, saying, <span class="p"><br /><br /></span> <span class="versiontext"><a href="/kjv/leviticus/1.htm">King James Bible</a></span><br /> And the LORD called unto Moses, and spake unto him out of the tabernacle of the congregation, saying, <span class="p"><br /><br /></span>
原因分析
你的XPath写法存在语法问题,并非xsltproc的局限性。你使用的.[contains(@class, 'versiontext')]嵌套写法属于XPath 2.0+的语法,而xsltproc默认仅支持XPath 1.0,因此无法解析这种写法;部分在线测试工具默认启用了XPath 2.0+,所以能正常运行。
修正后的XPath
以下两种写法均符合XPath 1.0规范,可在xsltproc中正常使用:
写法一:直接组合条件
//span[contains(@class, 'versiontext') and a[contains(@href, 'esv')]]
逻辑:筛选所有span元素,需同时满足两个条件——自身class包含versiontext,且子节点中存在a标签的href包含esv。
写法二:分步筛选后回溯父节点
//span[contains(@class, 'versiontext')]/a[contains(@href, 'esv')]/..
逻辑:先筛选出class为versiontext的span,再从中找到符合href条件的a标签,最后通过..回到父级span元素。
两种写法都能精准匹配到你HTML片段中包含ESV链接的span元素。
内容的提问来源于stack exchange,提问作者Zack
相关产品推荐
相关产品推荐

