XSL遍历同标签元素问题:学习XSD时XML转HTML效果不佳求助
Fixing Your XML-to-HTML XSL Transformation
First, let's make sure your XML is complete (since it was cut off in your question). Here's the full, well-formed version:
<?xml version="1.0" encoding="UTF-8"?> <sales> <division id="North"> <revenue>10</revenue> <growth>9</growth> <bonus>7</bonus> </division> <division id="South"> <revenue>4</revenue> <growth>3</growth> <bonus>4</bonus> </division> <division id="West"> <revenue>6</revenue> <growth>5</growth> <bonus>6</bonus> </division> </sales>
Now, here's a working XSLT stylesheet that converts this XML into a clean, readable HTML table. I'll break down the key parts so you can tweak it to fit your needs:
<?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> <head> <title>Sales Division Report</title> <style> table { border-collapse: collapse; width: 80%; margin: 20px auto; } th, td { border: 1px solid #ddd; padding: 8px; text-align: center; } th { background-color: #f2f2f2; } h1 { text-align: center; color: #333; } </style> </head> <body> <h1>Sales Division Performance</h1> <table> <tr> <th>Division</th> <th>Revenue</th> <th>Growth</th> <th>Bonus</th> </tr> <xsl:for-each select="sales/division"> <tr> <td><xsl:value-of select="@id"/></td> <td><xsl:value-of select="revenue"/></td> <td><xsl:value-of select="growth"/></td> <td><xsl:value-of select="bonus"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
Key Details to Note:
- Root Template: The
<xsl:template match="/">targets the very top of your XML document, so this is where we build our full HTML structure. - XPath Selectors:
sales/divisiontells the transformer to loop through every<division>element inside the<sales>root.@idgrabs theidattribute of each division (the@symbol is how you reference attributes in XPath).revenue,growth, etc., pull the text content of those child elements directly.
- Basic Styling: The embedded CSS makes the output table look polished—you can adjust colors, spacing, or layout here as needed.
Common Pitfalls You Might Be Hitting:
- Malformed XML: If your XML is incomplete (like the cut-off West division in your question), the transformer will throw errors. Always validate your XML first to ensure it's well-formed.
- Incorrect XPath: Double-check your
selectattributes. For example, if you triedselect="division"instead ofsales/divisionfrom the root, it won't find any elements. - Missing XSL Namespace: The
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"line is mandatory—without it, the processor won't recognize the XSLT tags. - Unlinked Stylesheet: To test this, save the XSL as
sales-transform.xsl, then add this line right after your XML declaration:
Open the XML file in a modern browser, and it should render the formatted HTML table automatically.<?xml-stylesheet type="text/xsl" href="sales-transform.xsl"?>
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

