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

时间:2021-04-06 10:49:02

标签: xslt-2.0

请建议从变量文本中获取 Xpath 表达式。因为 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>

XSLT 2.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>

1 个答案:

答案 0 :(得分:1)

在支持 xsl:evaluate 的 XSLT 3 中,您的代码如下所示(假设启用了 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

相关问题