0

查看地址http://www.w3schools.com/xml/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog_apply下的 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>

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

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

1 回答 1

5

W3C 学校没有告诉您的是 XSLT 的内置模板规则

当您这样做时,<xsl:apply-templates select="cd"/>您将定位在文档节点上,该节点是catalog元素的父节点。这样做select="cd"不会选择任何内容,因为cd它是元素的子catalog元素,而不是文档节点本身的子元素。只有catalog一个孩子。

(注意这catalog是 XML 的“根元素”。一个 XML 文档只能有一个根元素)。

但是,当您这样做时<xsl:apply-templates />,这相当于<xsl:apply-templates select="node()" />将选择catalog元素。这就是内置模板发挥作用的地方。您catalog的 XSLT 中没有匹配的模板,因此使用了内置模板。

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

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

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

<xsl:template match="/*">

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

于 2017-01-25T15:47:14.037 回答