【发布时间】:2021-09-02 16:30:21
【问题描述】:
我有一个动态 xpath 字符串提供给模板,我希望测试当前元素是否与模板中的 xpath 匹配。
我尝试过使用<xsl:evaluate/>,但我不确定它是如何使用的,或者它是否适合这项工作。
XSLT:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
xmlns:functx="http://www.functx.com"
version="2.0">
<!-- HTML output -->
<xsl:output
method="text"
encoding="UTF-8"
omit-xml-declaration="yes"
standalone="yes"
indent="no"
media-type="string"/>
<xsl:template match="*">
<!-- This xpathMatches variable will be dynamically generated -->
<xsl:variable name="xpathMatches" select="'s4|s2[@class=''class1'']|d3'"/>
<xsl:apply-templates mode="test">
<xsl:with-param name="xpathMatches" select="$xpathMatches" />
</xsl:apply-templates>
</xsl:template>
<xsl:template match="*" mode="test">
<xsl:param name="xpathMatches"/>
<xsl:variable name="xpathEval">
<xsl:evaluate xpath="$xpathMatches" context-item="."/>
</xsl:variable>
<!-- This doesn't work-->
<xsl:if test="$xpathEval">
<xsl:value-of select="name()"/>
</xsl:if>
</xsl:template>
</xsl:transform>
输入:
<div>
<s1 />
<s2 class="class1"/>
<s4 class="class7"/>
</div>
期望的输出:
s2
s4
由于 s2 和 s4 与 xpath 匹配,因此只应返回那些元素名称。 但目前测试对所有元素都返回 true。
【问题讨论】:
-
不确定在这种情况下“匹配”究竟是什么意思。你的字符串代表一个 relative 路径;因此,它只会在从
div的上下文中评估时匹配实际路径。我不明白样式表应该如何知道这一点。 -
为什么
s4不会被<xsl:variable name="xpathMatches" select="'s4|s2[@class=''class1'']|d3'"/>中的路径或模式选中?正如前面正确评论的那样,您的相对路径仅在div元素的上下文中才有意义,但在这种情况下,应该像s2元素一样选择s4元素。 -
是的,s4 也应该被选中。我没有正确写出想要的输出。