看看地址应用下面的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: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>我的问题是:为什么更改会破坏代码?在我看来,这两种情况的逻辑是相同的:
更新:
整个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>发布于 2017-01-25 15:47:14
W3C学校没有告诉您的是XSLT的内置模板规则。
执行<xsl:apply-templates select="cd"/>时,您将定位在文档节点上,该节点是catalog元素的父节点。执行select="cd"将不会选择任何内容,因为cd是catalog元素的子元素,而不是文档节点本身的子元素。只有catalog是个孩子。
(请注意,catalog是XML的“根元素”。XML文档只能有一个根元素)。
但是,当您执行<xsl:apply-templates />时,这与选择catalog元素的<xsl:apply-templates select="node()" />等效。这就是内置模板开始的地方。在XSLT中没有匹配catalog的模板,因此使用内置的模板。
<xsl:template match="*|/">
<xsl:apply-templates/>
</xsl:template>(在这里,*匹配任何元素)。因此,这个内置模板将选择catalog的子节点,从而匹配XSLT中的其他模板。
注意,在第二个示例中,您可以将模板匹配更改为.
<xsl:template match="/*">这将匹配catalog元素,因此<xsl:apply-templates select="cd" />将工作。
https://stackoverflow.com/questions/41855428
复制相似问题