2017-11-18 153 views
0

我有一個來自我使用的口徑的xml文件,並且在嵌套xsl:for-each時遇到了問題。xsl嵌套循環失敗

XML文件:

<?xml version='1.0' encoding='utf-8'?> 
<calibredb> 
    <record> 
    <title sort="Demon Under the Microscope, The">The Demon Under the Microscope</title> 
    <authors sort="Hager, Thomas"> 
     <author>Thomas Hager</author> 
    </authors> 
    </record> 
    <record> 
    <title sort="101 Things Everyone Should Know About Math">101 Things Everyone Should Know About Math</title> 
    <authors sort="Zev, Marc &amp; Segal, Kevin B. &amp; Levy, Nathan"> 
     <author>Marc Zev</author> 
     <author>Kevin B. Segal</author> 
     <author>Nathan Levy</author> 
    </authors> 
    </record> 
    <record> 
    <title sort="Biohazard">Biohazard</title> 
    <authors sort="Alibek, Ken"> 
     <author>Ken Alibek</author> 
    </authors> 
    </record> 
    <record> 
    <title sort="Infectious Madness">Infectious Madness</title> 
    <authors sort="WASHINGTON, HARRIET"> 
     <author>Harriet A. Washington</author> 
    </authors> 
    </record> 
    <record> 
    <title sort="Poetry Will Save Your Life">Poetry Will Save Your Life</title> 
    <authors sort="Bialosky, Jill"> 
     <author>Jill Bialosky</author> 
    </authors> 
    </record> 
</calibredb> 

XSL:

<?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 Calibre Collection</h2> 
    <table border="1"> 
     <tr bgcolor="#9acd32"> 
     <th>Title</th> 
     <th>Author</th> 
     </tr> 
     <xsl:for-each select="calibredb/record"> 
     <tr> 
     <td><xsl:value-of select="title" /></td> 
     <td><xsl:for-each select="authors"><xsl:value-of select="author" /></xsl:for-each></td> 
     </tr> 
     </xsl:for-each> 
    </table> 
    </body> 
    </html> 
</xsl:template> 
</xsl:stylesheet> 

看來,如果多個作者的存在,循環無法繼續深入。

任何人都可以給我一個關於如何正確格式化xsl的建議嗎?

謝謝!

回答

0

在XSLT 1.0 xsl:value-of只會給你第一個author的價值。

而是在內部的for-each,儘量選擇authors/author ...

<xsl:for-each select="authors/author"> 
    <xsl:value-of select="." /> 
</xsl:for-each> 

你可能也想輸出一個逗號或其他一些來分隔值...

選擇 authors
<xsl:for-each select="authors/author"> 
    <xsl:if test="position() > 1"> 
     <xsl:text>, </xsl:text> 
    </xsl:text> 
    <xsl:value-of select="."/> 
</xsl:for-each> 
0

這種失敗實際上與嵌套循環無關。 注意,每個record元件具有只有一個authors元件, 所以不需要內xsl:for-each select="authors" (它將使只有1圈)。

問題出在其他地方,即value-of指令。 您的情況是XSLT 1.0關於value-of, 奇怪功能的示例,許多XSLT用戶都不知道。

即使select短語檢索多個節點,然後 打印value-of第一其中,而不是整個序列, 和(IMHO),這是不平均XSLT用戶期望的內容。

只有在版本2.0時,這是以一種更直觀的方式。

value-of指令在XSLT 2.0將在這種情況下 整個序列打印,在它們之間插入的隔板指定 與separator屬性。

所以,如果你可以移動到版本2.0 ,只寫:

<xsl:for-each select="calibredb/record"> 
    <tr> 
    <td><xsl:value-of select="title" /></td> 
    <td><xsl:value-of select="authors/author" separator=", "/></td> 
    </tr> 
</xsl:for-each>