求助:使用XSL从XML提取输出(附示例及代码片段)
使用XSL提取XML中前N个元素并输出HTML的解决方案
看起来你想要实现用XSL从XML里提取指定数量的元素(比如前3个<cd>)并输出成HTML表格,我来帮你完善代码解决这个问题!
首先,先把你的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> <cd> <title>Greatest Hits</title> <artist>Dolly Parton</artist> <country>USA</country> <company>RCA</company> <price>9.90</price> <year>1982</year> </cd> <cd> <title>Still got the blues</title> <artist>Gary Moore</artist> <country>UK</country> <company>Virgin records</company> <price>10.20</price> <year>1990</year> </cd> <cd> <title>Eros</title> <artist>Eros Ramazzotti</artist> <country>EU</country> <company>BMG</company> <price>9.90</price> <year>1997</year> </cd> </catalog>
你提供的XSL代码还未完成,我帮你补充完整,实现提取前3个<cd>元素的需求:
<?xml version="1.0" encoding="US-ASCII" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html" omit-xml-declaration="no" indent="yes" /> <!-- 主模板,匹配根节点,构建HTML页面框架 --> <xsl:template match="/"> <html> <body> <h2>我的CD收藏(Top 3)</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>专辑名</th> <th>艺术家</th> <th>价格</th> </tr> <!-- 调用循环模板,传入要提取的数量3 --> <xsl:call-template name="loop"> <xsl:with-param name="current-pos" select="1"/> <xsl:with-param name="max-items" select="3"/> </xsl:call-template> </table> </body> </html> </xsl:template> <!-- 递归循环模板,处理每个指定位置的cd元素 --> <xsl:template name="loop"> <xsl:param name="current-pos"/> <xsl:param name="max-items"/> <!-- 判断当前位置是否在指定范围内,且存在对应cd元素 --> <xsl:if test="$current-pos <= $max-items and /catalog/cd[$current-pos]"> <tr> <td><xsl:value-of select="/catalog/cd[$current-pos]/title"/></td> <td><xsl:value-of select="/catalog/cd[$current-pos]/artist"/></td> <td><xsl:value-of select="/catalog/cd[$current-pos]/price"/></td> </tr> <!-- 递归调用自身,位置+1,继续处理下一个元素 --> <xsl:call-template name="loop"> <xsl:with-param name="current-pos" select="$current-pos + 1"/> <xsl:with-param name="max-items" select="$max-items"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet>
代码说明
- 主模板先搭建了HTML的基本结构,包括页面标题和表格表头,然后调用递归的
loop模板。 loop模板通过两个参数控制循环:current-pos是当前处理的元素位置,max-items是你想要提取的元素数量(这里设置为3)。- 用
<xsl:if>判断是否继续循环:只要当前位置不超过最大数量,且对应位置存在<cd>元素,就输出该元素的核心信息,然后递归调用自己,位置加1。 - 当位置超过指定数量或者没有对应元素时,循环自动终止。
最终输出
转换后会生成一个带有绿色表头的HTML表格,清晰展示前3张CD的专辑名、艺术家和价格信息。
内容的提问来源于stack exchange,提问作者Arigui Ahmed
相关产品推荐
相关产品推荐

