<apply-templates/> vs <应用模板选择= XSLT 中的 "..." />



查看地址下的XSLT代码http://www.w3schools.com/xml/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog_apply。。。下面是这个代码的第一部分(也是我问题的决定性部分):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>  
<xsl:apply-templates/>  
</body>
</html>
</xsl:template>

如果您现在只更改线路

<xsl:apply-templates/> 

<xsl:apply-templates select="cd"/>

转换不再有效。。。(代码现在如下:)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>  
<xsl:apply-templates select="cd"/>  <!--ONLY LINE OF CODE THAT WAS CHANGED-->
</body>
</html>
</xsl:template>

我的问题是:为什么更改会破坏代码?在我看来,这两种情况的逻辑都是一样的:

  1. 应用模板匹配"cd">
  2. 在模板"cd"中应用其他两个模板("title"+"artist")

更新:

整个xslt代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>  
<xsl:apply-templates/>  
</body>
</html>
</xsl:template>
<xsl:template match="cd">
<p>
<xsl:apply-templates select="title"/>  
<xsl:apply-templates select="artist"/>
</p>
</xsl:template>
<xsl:template match="title">
Title: <span style="color:#ff0000">
<xsl:value-of select="."/></span>
<br />
</xsl:template>
<xsl:template match="artist">
Artist: <span style="color:#00ff00">
<xsl:value-of select="."/></span>
<br />
</xsl:template>
</xsl:stylesheet>

以下是xml的摘录:

<?xml version="1.0" encoding="UTF-8"?>
<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>
......
</catalog>
W3C学校没有告诉你的是XSLT的内置模板规则。

执行<xsl:apply-templates select="cd"/>时,您位于文档节点上,该节点是catalog元素的父节点。执行select="cd"将不选择任何内容,因为cdcatalog元素的子级,而不是文档节点本身的子级。只有catalog是孩子。

(注意,catalog是XML的"根元素"。一个XML文档只能有一个根元素)。

但是,当执行<xsl:apply-templates />时,这相当于<xsl:apply-templates select="node()" />,它将选择catalog元素。这就是内置模板的作用所在。XSLT中没有与catalog匹配的模板,因此使用了内置模板。

<xsl:template match="*|/">
<xsl:apply-templates/>
</xsl:template>

(此处*匹配任何元素)。因此,这个内置模板将选择catalog的子节点,从而匹配XSLT中的其他模板。

请注意,在第二个示例中,您可以将模板匹配更改为。。。

<xsl:template match="/*">

这将匹配catalog元素,因此<xsl:apply-templates select="cd" />将起作用。

最新更新