XSLT处理嵌套XML问题:订单商品列表填充排序功能实现求助
问题原因
你现有代码的错误主要集中在订单表格的实现部分:
- 表头结构不符合CSS定义:原代码表头写了6个单元格(3个
<th>+3个<td>),但实际只需要3列对应商品编号、商品描述、购买数量。 - 未遍历商品节点:没有循环处理每个
<order>下的<item>子节点,只尝试在表头直接取值,无法输出所有商品。 - 缺少指定排序规则:没有针对商品添加「数量降序、数量相同则商品ID升序」的排序逻辑。
修正后完整XSLT代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" doctype-system="about:legacy-compat" encoding="UTF-8" indent="yes" /> <xsl:template match="/"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Customer Orders at Cairn Camping</title> <link href="cstyles.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="wrap"> <header> <h1>Cairn Camping Store</h1> </header> <section> <h1>Customer Orders</h1> <article> <xsl:for-each select="customers/customer"> <xsl:sort select="name" /> <table class="cdata"> <tr> <th>Name</th> <td> <xsl:value-of select="name" /> </td> </tr> <tr> <th>Address</th> <td> <xsl:value-of select="street"/> <br /> <xsl:value-of select="city" /> , <xsl:value-of select="state" /> <br /> <xsl:value-of select="zip" /> </td> </tr> <tr> <th>Customer ID</th> <td> <xsl:value-of select="@cid" /> </td> </tr> </table> <xsl:for-each select ="orders/order"> <xsl:sort select="@oid" order="descending" /> <table class="items"> <thead> <tr> <th colspan="3"> <span class="date"> <xsl:value-of select="date" /> </span> <span class="oid"> <xsl:value-of select="@oid" /> </span> </th> </tr> <tr> <th>Item No.</th> <th>Description</th> <th>Qty</th> </tr> </thead> <tbody> <xsl:for-each select="item"> <!-- 排序规则:先按数量降序,相同则按商品ID升序 --> <xsl:sort select="qty" data-type="number" order="descending" /> <xsl:sort select="@iid" order="ascending" /> <tr> <td><xsl:value-of select="@iid" /></td> <td><xsl:value-of select="description" /></td> <td><xsl:value-of select="qty" /></td> </tr> </xsl:for-each> </tbody> </table> </xsl:for-each> </xsl:for-each> </article> </section> </div> </body> </html> </xsl:template> </xsl:stylesheet>
核心修改说明
- 修正了订单表格表头结构,仅保留3个表头项,和CSS的列宽定义完全匹配
- 新增了
<xsl:for-each select="item">循环遍历每个订单下的所有商品 - 给商品添加了两层排序规则:
- 第一层按
<qty>数值降序排列,指定data-type="number"避免字符串排序错误 - 数量相同的情况下,按商品的
iid属性字母升序排列
- 第一层按
- 修正了原有
<br>标签的闭合写法,避免HTML语法错误
内容的提问来源于stack exchange,提问作者user17504108
相关产品推荐
相关产品推荐

