乐闻世界logo
搜索文章和话题

What is XSLT and how do you use it to transform XML documents?

2月21日 14:22

XSLT (Extensible Stylesheet Language Transformations) is a language used to transform XML documents into other formats. It can convert XML to HTML, text, other XML formats, and even to other document formats like PDF.

Basic Concepts of XSLT

XSLT is part of XSL (Extensible Stylesheet Language), which consists of three parts:

  1. XSLT: Used to transform XML documents
  2. XPath: Used to navigate within XML documents
  3. XSL-FO: Used to format XML documents

Basic Structure of XSLT

xml
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- Template definition --> <xsl:template match="/"> <html> <body> <h1>Book List</h1> <xsl:apply-templates select="bookstore/book"/> </body> </html> </xsl:template> <!-- Another template --> <xsl:template match="book"> <div> <xsl:value-of select="title"/> <xsl:text> - </xsl:text> <xsl:value-of select="author"/> </div> </xsl:template> </xsl:stylesheet>

Common XSLT Elements

1. Template Elements

xml
<xsl:template match="pattern"> Template content </xsl:template> <xsl:apply-templates select="expression"/>

2. Output Elements

xml
<xsl:value-of select="expression"/> <xsl:copy/> <xsl:copy-of select="expression"/> <xsl:text>Text content</xsl:text>

3. Control Elements

xml
<!-- Conditional statement --> <xsl:if test="condition"> Content </xsl:if> <!-- Multiple condition selection --> <xsl:choose> <xsl:when test="condition1"> Content1 </xsl:when> <xsl:when test="condition2"> Content2 </xsl:when> <xsl:otherwise> Default content </xsl:otherwise> </xsl:choose> <!-- Loop --> <xsl:for-each select="expression"> Content </xsl:for-each>

4. Variables and Parameters

xml
<xsl:variable name="varName" select="expression"/> <xsl:param name="paramName" select="expression"/> <xsl:value-of select="$varName"/>

5. Sorting

xml
<xsl:for-each select="book"> <xsl:sort select="price" order="ascending"/> <xsl:value-of select="title"/> </xsl:for-each>

Practical Application Examples of XSLT

1. XML to HTML Conversion

Input XML (books.xml):

xml
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="web"> <title>XML Guide</title> <author>John Doe</author> <price>39.95</price> </book> <book category="database"> <title>SQL Basics</title> <author>Jane Smith</author> <price>29.99</price> </book> </bookstore>

XSLT Stylesheet (books.xsl):

xml
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" encoding="UTF-8"/> <xsl:template match="/"> <html> <head> <title>Book List</title> <style> table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #4CAF50; color: white; } </style> </head> <body> <h1>Book List</h1> <table> <tr> <th>Title</th> <th>Author</th> <th>Price</th> </tr> <xsl:for-each select="bookstore/book"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="author"/></td> <td><xsl:value-of select="price"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

2. XML to XML Conversion

xml
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <catalog> <xsl:for-each select="bookstore/book"> <item> <name><xsl:value-of select="title"/></name> <writer><xsl:value-of select="author"/></writer> <cost><xsl:value-of select="price"/></cost> </item> </xsl:for-each> </catalog> </xsl:template> </xsl:stylesheet>

3. Conditional Processing

xml
<xsl:template match="book"> <div class="book"> <xsl:attribute name="style"> <xsl:choose> <xsl:when test="price > 30"> color: red; </xsl:when> <xsl:when test="price > 20"> color: blue; </xsl:when> <xsl:otherwise> color: green; </xsl:otherwise> </xsl:choose> </xsl:attribute> <xsl:value-of select="title"/> - $<xsl:value-of select="price"/> </div> </xsl:template>

Using XSLT in Different Languages

1. Java

java
import javax.xml.transform.*; import javax.xml.transform.stream.*; // Create transformer factory TransformerFactory factory = TransformerFactory.newInstance(); // Create transformer StreamSource xsltSource = new StreamSource(new File("books.xsl")); Transformer transformer = factory.newTransformer(xsltSource); // Execute transformation StreamSource xmlSource = new StreamSource(new File("books.xml")); StreamResult htmlResult = new StreamResult(new File("books.html")); transformer.transform(xmlSource, htmlResult);

2. Python (lxml)

python
from lxml import etree # Parse XML and XSLT xml_doc = etree.parse("books.xml") xslt_doc = etree.parse("books.xsl") # Create transformer transform = etree.XSLT(xslt_doc) # Execute transformation result = transform(xml_doc) # Save result result.write("books.html", pretty_print=True)

3. JavaScript (Browser)

javascript
// Reference XSLT in XML document <?xml-stylesheet type="text/xsl" href="books.xsl"?> // Or use in JavaScript const xsltProcessor = new XSLTProcessor(); const xsltDoc = document.implementation.createDocument("", "", null); xsltDoc.async = false; xsltDoc.load("books.xsl"); xsltProcessor.importStylesheet(xsltDoc); const xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.async = false; xmlDoc.load("books.xml"); const result = xsltProcessor.transformToDocument(xmlDoc);

Advanced XSLT Features

1. Template Modes

xml
<xsl:template match="book" mode="summary"> <summary><xsl:value-of select="title"/></summary> </xsl:template> <xsl:template match="book" mode="detail"> <detail> <title><xsl:value-of select="title"/></title> <author><xsl:value-of select="author"/></author> </detail> </xsl:template> <xsl:apply-templates select="book" mode="summary"/>

2. Named Templates

xml
<xsl:template name="formatPrice"> <xsl:param name="price"/> $<xsl:value-of select="format-number($price, '#,##0.00')"/> </xsl:template> <xsl:call-template name="formatPrice"> <xsl:with-param name="price" select="price"/> </xsl:call-template>

3. Keys and Indexes

xml
<xsl:key name="book-by-author" match="book" use="author"/> <xsl:for-each select="book[count(. | key('book-by-author', author)[1]) = 1]"> <author><xsl:value-of select="author"/></author> </xsl:for-each>

XSLT Best Practices

  1. Use template matching: Prioritize template matching over for-each
  2. Avoid deep nesting: Maintain XSLT code readability
  3. Use variables: Avoid repeated calculations
  4. Optimize XPath: Use efficient XPath expressions
  5. Modular design: Break complex transformations into multiple templates

XSLT is a powerful tool for processing XML data transformations. Mastering XSLT can greatly improve the efficiency and flexibility of XML data processing.

标签:XML