XSL技术实现:根据XML子节点不同值生成多张表格
Split XML Album Data into Grouped Tables by Child Node Value
Alright, let's tackle this problem—you want to split your XML album entries into separate tables based on the value of a specific child node (like Country, which is present in your sample). XSLT is the perfect tool for this, and here's a practical, customizable solution:
XSLT Code to Generate Grouped Tables
We'll use Country as the grouping key (you can swap this out for Artist or any other node if needed):
<?xml version="1.0" encoding="ISO8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Create an index to group albums by their Country value --> <xsl:key name="albums-by-country" match="Album" use="Country"/> <xsl:template match="/Albums"> <html> <body> <!-- Loop through each unique Country value --> <xsl:for-each select="Album[generate-id() = generate-id(key('albums-by-country', Country)[1])]"> <!-- Optional: Sort countries alphabetically for cleaner output --> <xsl:sort select="Country"/> <!-- Heading for the current country's table --> <h2>Albums from <xsl:value-of select="Country"/></h2> <!-- Table structure for the country's albums --> <table border="1"> <tr> <th>Album Name</th> <th>Artist</th> </tr> <!-- Populate table with all albums in this country group --> <xsl:for-each select="key('albums-by-country', Country)"> <tr> <td><xsl:value-of select="Name"/></td> <td><xsl:value-of select="Artist"/></td> </tr> </xsl:for-each> </table> <br/> <!-- Add spacing between tables --> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet>
How This Works
<xsl:key>: Builds an efficient index of all albums grouped by theirCountryvalue, so we don't have to scan the entire XML repeatedly.generate-id()Check: Ensures we only create one table per unique country (no duplicate tables for the same region).- Customizable Grouping: If you want to group by
Artistinstead, just replace every instance ofCountrywithArtistin the code. - Sorting: The
<xsl:sort>tag organizes groups alphabetically—remove it if you prefer the original order from the XML.
Example Output (Markdown Representation)
Albums from USA
| Album Name | Artist |
|---|---|
| Empire Burlesque | Bob Dylan |
| [Other USA albums] | [Corresponding Artists] |
Albums from UK
| Album Name | Artist |
|---|---|
| [UK Album 1] | [Artist Name] |
| [UK Album 2] | [Artist Name] |
内容的提问来源于stack exchange,提问作者Roee Vakrat
相关产品推荐
相关产品推荐

