关于XSLT的初学者问题"apply-templates"

Kev*_*vin 1 xml xslt

对于这样一个非常简单的XML:

<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>9.90</price>
        <year>1988</year>
    </cd>
    <cd>
        <title>Greatest Hits</title>
        <artist>Dolly Parton</artist>
        <country>USA</country>
        <company>RCA</company>
        <price>9.90</price>
        <year>1982</year>
    </cd>
</catalog>
Run Code Online (Sandbox Code Playgroud)

和一个简单的xslt:

<xsl:template match="/">
 <xsl:apply-templates/>  
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

为什么会产生如下输出:

Empire Burlesque
Bob Dylan
USA
Columbia
10.90
1985

Hide your heart
Bonnie Tyler
UK
CBS Records
9.90
1988

Greatest Hits
Dolly Parton
USA
RCA
9.90
1982
Run Code Online (Sandbox Code Playgroud)

所有XML标签都去了哪里?我应该<xsl:apply-templates/><xsl:copy>标签包围以 使其工作吗?

Way*_*ett 5

这是因为内置模板访问所有元素并打印文本和属性节点的值(只要模板适用于它们).有关完整说明,请参阅我之前问题的答案:

默认情况下打印XSLT 1.0文本节点

您可以使用它xsl:copy来执行身份转换:

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

这将输出源文档的副本.