引用变量的 XSLT

XSLT referencing to a variable

我正在努力解决与这个简单示例有关的问题。为什么输出的不是书的日期,而是空的 <test/> 标签?

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

这里是图书示例 XML:

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

两个问题,date 元素也在该名称空间中,因此您需要 <xsl:value-of select="b:date"/> 而不是 <xsl:value-of select="date"/>

要在作为结果树片段的变量中输出 elementsv 或一般节点,您需要 xsl:copy-of,而不是 xsl:value-of(它只是创建一个文本节点),因此您至少需要 <xsl:copy-of select="$Books"/>.