2017-01-25 27 views
0

查看地址http://www.w3schools.com/xml/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog_apply下的XSLT代碼...下面您會找到此代碼的第一部分(以及一個決定性的我的問題):<apply-templates /> vs XSLT中的<apply-templates select =「...」/>

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

轉型並不W改爲只行掃了...(現在,該代碼如下所示:)

<?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」申請其他兩個模板(「標題」 +「藝術家」)

UPDATE:

整個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> 
+0

你可以編輯你的問題來包含XML的樣本,所以這個問題可以是「獨立的」,並不需要點擊W3Schools來查看。謝謝! –

回答

3

什麼W3C學校不告訴你的是關於XSLT的Built-in Template Rules

當您執行<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" />會工作。