2015-11-05 77 views
-1

我有一個.xml文件,我應該用XSL轉換成html文件。XSL:「爲每個選擇」功能不能正常工作

我的XML:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<?xml-stylesheet type="text/xsl" href="test.xsl" ?> 
<Company> 

<SectionA> 
    <Employee>Peter Barry</Employee> 
    <Employee>Lisa Stewart</Employee> 
    <Employee>Harry Rogers</Employee> 
</SectionA> 

<SectionB> 
    <Employee>Tom Riddle</Employee> 
</SectionB> 

</Company> 

在我的HTML文件的輸出應該是這樣的: 「彼得·巴里,麗莎·斯圖爾特,哈利·羅傑斯」。

問題是for-each功能在這種情況下不起作用! 我的XSL代碼:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:template match="/"> 
<html> 
<body> 

<h2>All</h2> 

<table> 

<td> 
    <xsl:for-each select="Company/SectionA"> 
    <xsl:value-of select="Employee"/> 
    </xsl:for-each> 
</td> 


</table> 


</body> 
</html> 
</xsl:template> 

</xsl:stylesheet> 

在HTML它只顯示第一個僱員的名字(即「彼得·巴里」)。我如何才能做到這一點,以展示每一個元素?

+0

請出示一個** **重複性例子。我們不知道你的代碼是幹什麼的,不知道它在哪個上下文中執行。也就是說,一個空的'xsl:for-each'不會做任何事情。把東西放進去,例如'XSL:價值of'。 - 另外,請將您的預期輸出**顯示爲代碼**。 –

+0

對不起,我現在把這兩個代碼現在寫入我的文章! –

+0

順便說一句,'​​'元素需要位於''內。 – Flynn1179

回答

0

如果你想在A部分每個員工一排,比使用:

<xsl:template match="/"> 
    <table> 
     <xsl:for-each select="Company/SectionA/Employee"> 
      <tr><td><xsl:value-of select="."/></td></tr> 
     </xsl:for-each> 
    </table> 
</xsl:template> 

你現在的樣子,你是在SectionA<xsl:value-of select="Employee"/>上下文返回第一的價值僅兒童員工 - 這就是XSLT 1.0中的工作原理。另外,您只創建一個表格單元格而沒有行。

1

使用的for-each是不是在這種情況下,最好的選擇,這將是更好地定義一個模板來處理每一個員工,像這樣:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/"> 
    <html> 
     <body> 
     <h2>All</h2> 
     <xsl:apply-templates select="Company/SectionA"/> 
     </body> 
    </html> 
    </xsl:template> 

    <xsl:template match="SectionA"> 
    <table> 
     <xsl:apply-templates/> 
    </table> 
    </xsl:template> 

    <xsl:template match="Employee"> 
    <tr> 
     <td><xsl:value-of select="."/></td> 
    </tr> 
    </xsl:template>   
</xsl:stylesheet>