如何将变量文本制作为Xpath表达式



请建议从变量文本中获取Xpath表达式。As xpath表达式以文本形式存储在变量中。根据早期的建议,建议评估功能,但无法获得。

XML:

<article>
<float>
<fig id="fig1">Figure 1</fig>
<fig id="fig2" type="color">Figure 2</fig>
<fig id="fig3" type="color">Figure 3</fig>
<fig id="fig4" type="color">Figure 4</fig>
</float>

XSLT2.0:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:param name="varColorFig"><xsl:text>//float/fig[@type='color']</xsl:text></xsl:param><!-- Xpath stored in variable as a text-->
<!--xsl:variable name="names" as="element(name)*"><xsl:evaluate xpath="$varColorFig" context-item="."/></xsl:variable-->
<xsl:template match="article">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<xsl:element name="ColorFigCount">
<xsl:if test="count(//float/fig[@type='color']) gt 0">
<a><xsl:value-of select="count(//float/fig[@type='color'])"/></a>
</xsl:if><!--real Xpath expression format-->

<xsl:if test="count($varColorFig) gt 0">
<b><xsl:value-of select="count($varColorFig)"/></b>
</xsl:if><!-- xpath stored in variable as text, then needs to get as Xpath here, but it is not processing as Xpath.-->
</xsl:element>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

必需结果:<b>3</b>是必需的,但现在得到1。

<article>
<float>
<fig id="fig1">Figure 1</fig>
<fig id="fig2" type="color">Figure 2</fig>
<fig id="fig3" type="color">Figure 3</fig>
<fig id="fig4" type="color">Figure 4</fig>
</float>
<ColorFigCount><a>3</a><b>3</b></ColorFigCount>
</article>

在支持xsl:evaluate的XSLT3中,您的代码如下所示(假设启用了expand-text="yes"(:

<xsl:param name="varColorFig"><xsl:text>//float/fig[@type='color']</xsl:text></xsl:param><!-- Xpath stored in variable as a text-->
<xsl:variable name="names" as="element(fig)*"><xsl:evaluate xpath="$varColorFig" context-item="."/></xsl:variable>
<xsl:template match="article">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<colorFigCount>{count($names)}</colorFigCount>
</xsl:copy>
</xsl:template>

xsl:param可以缩短为<xsl:param name="varColorFig">//float/fig[@type='color']</xsl:param>,我认为不需要xsl:text

最新更新