Amazing XSLT / XPath Expression Type Behavior

I have encountered type-related behavior in XSLT / XPath that I cannot explain. Here's an XSLT snippet that shows the problem (it's not a very useful XSLT, of course, but it provides a pretty minimal demo of my question):

    <?xml version="1.0"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:template match="/">
            <xsl:variable name="root">
                <xsl:sequence select="root(.)"/>
            </xsl:variable>
            <xsl:if test="root(.) is  $root">
                Match
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>

      

You will see that "Match" is not displayed. However, if you add as="node()"

to <xsl:variable name="root">

, then "Match" is displayed.

Can someone please explain, help me understand why?

You can connect this XSLT to http://xslttest.appspot.com to investigate the problem. Any input XML will work (for example <?xml version="1.0"?><foo/>

).

Thanks, Josh.

+3


source to share


1 answer


To find out the difference between sequence and variable, you can go to the next link.

To summarize, xsl:variable

without the attribute as

creates a new document (having its own root node). Using an attribute as

helps create an atomic value or sequence. Here the variable will not be the root node, but will reference the sequence (s) it contains.

Using:

<xsl:variable name="root">
            <xsl:sequence select="root(.)"/>
</xsl:variable>

      

With a condition, <xsl:if test="root(.) is $root">

you are checking if the root of the input XML document is the same as the root of the variable root

that is false

.

And when you use:



<xsl:variable name="root" as="node()">

      

The condition root(.) is $root

is evaluated both true

as the root input document and the sequence generated by the variable root

are the same.

And of course, as pointed out in michael.hor257k

, this stylesheet must be versioned 2.0

.

EDIT: Declaring a variable like this will also result in a conditiontrue()

<xsl:variable name="root" select="root(.)"/>

      

+2


source







All Articles