XSL嵌套SORT问题

时间:2017-07-18 20:56:04

标签: xml sorting xslt nested

我需要显示两个嵌套的FOR-EACH的结果,以字母顺序显示两者的所有结果我尝试使用节点集,但它不起作用。 如何对For-Each的所有结果进行排序?

数据:

<?xml version="1.0" encoding="UTF-8"?>
<list>
<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>

</catalog>
<catalog>  
<cd>
    <title>When a man loves a woman</title>
    <artist>Zercy Sledge</artist>
    <country>USA</country>
    <company>Atlantic</company>
    <price>8.70</price>
    <year>1987</year>
  </cd>
  <cd>
    <title>Black angel</title>
    <artist>Avage Rose</artist>
    <country>EU</country>
    <company>Mega</company>
    <price>10.90</price>
    <year>1995</year>
  </cd>
  <cd>
    <title>1999 Grammy Nominees</title>
    <artist>Iany</artist>
    <country>USA</country>
    <company>Grammy</company>
    <price>10.20</price>
    <year>1999</year>
  </cd>

</catalog>

</list>

代码:

<?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 CD Collection</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th>Title</th>
      <th>Artist</th>
    </tr>
    <xsl:for-each select="list/catalog">
 <xsl:for-each select="cd">
      <xsl:sort select="artist"/>
     <tr>
      <td><xsl:value-of select="title"/></td>
    <td><xsl:value-of select="artist"/></td>
  </tr>
  </xsl:for-each>
</xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>

结果: Result: 预期: Expected:

1 个答案:

答案 0 :(得分:1)

您要分别对每个catalog进行排序。要将所有cd排在一起,无论其catalog如何,请执行以下操作:

<xsl:template match="/">
    <html>
        <body>
        <h2>My CD Collection</h2>
        <table border="1">
            <tr bgcolor="#9acd32">
                <th>Title</th>
                <th>Artist</th>
            </tr>
            <xsl:for-each select="list/catalog/cd">
                <xsl:sort select="artist"/>
                <tr>
                    <td><xsl:value-of select="title"/></td>
                    <td><xsl:value-of select="artist"/></td>
                </tr>
            </xsl:for-each>
        </table>
        </body>
    </html>
</xsl:template>