Rudramuni TP
Rudramuni TP

Reputation: 1276

How to make variable text as Xpath expression

Please suggest to get Xpath expression from the variable text. As xpath expression is stored in a variable as a text. From earlier suggestions were suggesting evaluate function, but unable to get.

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>

Required Result: <b>3</b> is the required, but now getting 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>

Upvotes: 0

Views: 181

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

In XSLT 3 with xsl:evaluate support your code would look as follows (assumes expand-text="yes" is enabled):

  <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>

The xsl:param could be shortened to <xsl:param name="varColorFig">//float/fig[@type='color']</xsl:param>, I don't see a need for xsl:text.

Upvotes: 1

Related Questions