2017-11-18 154 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>