XSLT referencing to a variable

Viewed 24

I'm struggling with a problem which comes up to this simple example. Why the output isn't dates of books, but just empty <test/> tag?

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:b="http://www.demo.com/book">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:variable name="Books">
        <xsl:for-each select="//b:books/b:book">
            <xsl:element name="qq"><xsl:value-of select="date"/></xsl:element>
        </xsl:for-each>
    </xsl:variable>


    <xsl:template match="/">
        <xsl:element name="test">
            <xsl:value-of select="$Books"/>
        </xsl:element>

    </xsl:template>
</xsl:stylesheet>

Here's the sample XML for books:

<?xml version="1.0" encoding="utf-8"?>
<b:books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.demo.com" xmlns:b="http://www.demo.com" xsi:schemaLocation="http://www.demo.com book.xsd">
    <b:book id="1">
        <name>Hamlet</name>
        <date>2001-05-04</date>
        <authorId>1</authorId>
        <availability>false</availability>
    </b:book>
    <b:book id="2">
        <name>Macbeth</name>
        <date>2000-12-13</date>
        <authorId>1</authorId>
        <availability>false</availability>
    </b:book>
</b:books>
1 Answers

Two issues, the date element is also in that namespace so you need <xsl:value-of select="b:date"/> instead of <xsl:value-of select="date"/>.

To output elementsv or nodes in general in a variable that is a result tree fragment you need xsl:copy-of, not xsl:value-of (which just creates a text node) so you want at least <xsl:copy-of select="$Books"/>.

Related