How to use XSL to transform XML content

Extensible Stylesheet Language (XSL) is an XML-based language for creating stylesheets. You can use stylesheets (also known as transforms), with the help of an XSLT processor, to convert your XML document into other documents. In other words you can use an XSLT stylesheet to transform one type of XML to a different XML structure. An even more popular use of XSLT is to convert an XML document into an HTML document that can be displayed in a browser.

Note: You can find more information about XLS from online tutorials at http://www.w3schools.com/xsl, or the standard itself at http://www.w3.org/Style/XSL.

Before you can perform a transformation, you need to create an XSL stylesheet that defines how the conversion should be applied. XSL is a complex standard—in fact, it can be considered a genuine language of its own with conditional logic, looping structures, and more. If you want to transform BooksList (explained in the articles How to use XML attributes or How to use XMLTextWriter to create an XML document in C# and How to use XMLTextWriter to create an XML document in VB.NET) in into HTML, you can use use the simple stylesheet shown here:

 

<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” version=”1.0″>

<xsl:template match=”/”>

<html>

<body>

<xsl:apply-templates select=”BooksList/Book” />

</body>

</html>

</xsl:template>

<xsl:template match=”Book”>

<hr/>

<h3><u><xsl:value-of select=”Title” /></u></h3>

<b> ISBN-13: </b> <xsl:value-of select=”ISBN-13″ /><br/>

<b> Author: </b> <xsl:value-of select=”Author” /><br/>

<b>Price: </b> <xsl:value-of select=”Price” /><br/>

</xsl:template>

</xsl:stylesheet>

 

Every XSL file has a root <stylesheet> element. The <stylesheet> element can contain one or more templates (the sample file has two). In this example, the first <template> element matches the root element. When it finds it, it outputs the tags necessary to start an HTML page and then uses the <applytemplates> command to branch off and perform processing for any <Book> elements that are children of <BooksList>, as follows:

 

<xsl:template match=”/”>

<html>

<body>

<xsl:apply-templates select=”BooksList/Book” />

</body>

</html>

</xsl:template>

 

Each time the <Book> tag is matched, a horizontal line is added, and a heading is created. Information about the <ISBN-13>, <Author>, and <Price> tag is extracted and written to the page using the <value-of> command. Here’s the full template for transforming <Book> elements:

 

<xsl:template match=”Book”>

<hr/>

<h3><u><xsl:value-of select=”Title” /></u></h3>

<b> ISBN-13: </b> <xsl:value-of select=”ISBN-13″ /><br/>

<b> Author: </b> <xsl:value-of select=”Author” /><br/>

<b>Price: </b> <xsl:value-of select=”Price” /><br/>

</xsl:template>