Siva Senthil
Siva Senthil

Reputation: 610

Using the Xpath stored in Xslt variable

I have an XML file which has XPath string in its attribute. Something like this -


    <root>
     <element name="A" visible="True" text="Display Text " selected="True" />
     <element name="B" visible="True" text="DisplayText" visibilityCondition="//element[@name='A']/@selected" />
    </root>
    

Now using XSLT I want to show or hide content based on visibilityCondition of element named A. i.e.

    <xsl:for-each select="element">
     <xsl:variable name="visibleCondition" select="@visibilityCondition" />
     <xsl:choose>
      <xsl:when test="boolean($visibleCondition)">
       <xsl:when test="$visibleCondition">
        <xsl:if test="$visibleCondition='True'">
         ...
        </xsl:if>
        <xsl:otherwise>
         ...
        </xsl:otherwise>
       </xsl:when>
      </xsl:choose>
     </xsl:foreach>
    

The problem is the if condition always fails since, $visibleCondition has a value //element[@name='A']/@selected whereas I want to get the XPath parsed and match against the actual value in the selected attribute which is True. How do I go about achieving this?

Upvotes: 1

Views: 885

Answers (2)

Tobias Klevenz
Tobias Klevenz

Reputation: 1645

You cannot evaluate a string that you have stored in an attribute as XPath, which is the same as if you construct an xpath that you want to evaluate, without an extension.

In your example boolean($visibleCondition) will only check if the @visibilityCondtion attribute is present but will not evaluate the expression stored in the attribute.

You can check the saxon extension linked in the answer here or have a look at dyn:evaluate from exslt.

Upvotes: 1

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

this stylesheet uses EXSLT dynamic, however, this is not working using saxon processor.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:dyn="http://exslt.org/dynamic"
    extension-element-prefixes="dyn"
    version="1.1">

    <xsl:template match="root">

    <xsl:for-each select="element">
        <xsl:variable name="visibleCondition" select="@visibilityCondition" />
        <xsl:if test="dyn:evaluate($visibleCondition)='True'">
                SuCcEsS!
        </xsl:if>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

I tried it with XALAN 2.7.1 in http://xsltransform.net/ and it works.

Upvotes: 1

Related Questions