XSL Transformations (XSLT)

XSL Transformations (XSLT)

For programmers laboring in the trenches with XML, XSLT is one of the brightest stars in the XML universe. XSLT stands for Extensible Stylesheet Language Transformations. It is a language for converting XML documents from one format to another. Although it can be applied in a variety of ways, XSLT enjoys two primary uses:

  • Converting XML documents into HTML documents

  • Converting XML documents into other XML documents

The first application turning XML into HTML is useful for building Web pages and other browser-based documents in XML. XML defines the content and structure of data, but it doesn t define the data s appearance. Using XSLT to generate HTML from XML is a fine way to separate content from appearance and to build generic documents that can be displayed however you want them displayed. You can also use cascading style sheets (CSS) to layer appearance over XML content, but XSLT is more versatile than CSS and provides substantially more control over the output.

XSLT is also used to convert XML document formats. Suppose company A expects XML invoices submitted by company B to conform to a particular format (that is, fit a particular schema), but company B already has an XML invoice format and doesn t want to change it to satisfy the whims of company A. Rather than lose company B s business, company A can use XSLT to convert invoices submitted by company B to company A s format. That way both companies are happy, and neither has to go to extraordinary lengths to work with the other. XML-to-XML XSLT conversions are the nucleus of middleware applications such as Microsoft BizTalk Server that automate business processes by orchestrating the flow of information.

Figure 13-13 illustrates the mechanics of XSLT. You feed a source document (the XML document to be transformed) and an XSL style sheet that describes how the document is to be transformed to an XSLT processor. The XSLT processor, in turn, generates the output document using the rules in the style sheet.

Figure 13-13

XSL Transformations.

MSXML is an XSLT processor. So is the XslTransform class located in the FCL s System.Xml.Xsl namespace. XslTransform is one of the coolest classes in the FCL. It s exceedingly simple to use, and it s an essential tool to have at your disposal when the need arises to programmatically convert XML documents from one format to another. The following sections describe how to put XslTransform to work.

Converting XML to HTML on the Client

If you ve never worked with XSLT before, a great way to get acquainted with it is to build a simple XML document and transform it to HTML using Internet Explorer (which, under the hood, relies on MSXML to perform XSL transformations). Here s how:

  1. Copy Figure 13-16 s Guitars.xml and Guitars.xsl to the directory of your choice.

  2. Temporarily delete (or comment out) the following statement in Guitars.xml:

    <?xml-stylesheet type="text/xsl" href="Guitars.xsl"?>

  3. Open Guitars.xml in Internet Explorer. The file is displayed as XML (Figure 13-14).

  4. Restore (or uncomment) the statement you deleted (or commented out) in step 2.

  5. Open Guitars.xml again in Internet Explorer. This time, the file is displayed as HTML (Figure 13-15).

    Figure 13-14

    Guitars.xml displayed without XSLT.

    Figure 13-15

    Guitars.xml displayed with XSLT.

    Guitars.xml

    <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="Guitars.xsl"?> <Guitars> <Guitar> <Make>Gibson</Make> <Model>SG</Model> <Year>1977</Year> <Color>Tobacco Sunburst</Color> <Neck>Rosewood</Neck> </Guitar> <Guitar> <Make>Fender</Make> <Model>Stratocaster</Model> <Year>1990</Year> <Color>Black</Color> <Neck>Maple</Neck> </Guitar> </Guitars>
    Figure 13-16

    XML file and an XSL style sheet for transforming it into HTML.

    Guitars.xsl

    <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <body> <h1>My Guitars</h1> <hr /> <table width="100%" border="1"> <tr bgcolor="gainsboro"> <td><b>Make</b></td> <td><b>Model</b></td> <td><b>Year</b></td> <td><b>Color</b></td> <td><b>Neck</b></td> </tr> <xsl:for-each select="Guitars/Guitar"> <tr> <td><xsl:value-of select="Make" /></td> <td><xsl:value-of select="Model" /></td> <td><xsl:value-of select="Year" /></td> <td><xsl:value-of select="Color" /></td> <td><xsl:value-of select="Neck" /></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

What happened? The statement

<?xml-stylesheet type="text/xsl" href="Guitars.xsl"?>

is a processing instruction informing Internet Explorer that Guitars.xsl is a style sheet containing instructions for converting the content found in Guitars.xml to another format. IE downloaded the style sheet and ran it against Guitars.xml, producing HTML.

Most XSL transformations are template-driven. In Guitars.xsl, the statement

<xsl:template match="/">

marks the beginning of a template that applies to the entire document. / is an XPath expression that signifies the root of the document. The first several statements inside the template output the beginnings of an HTML document that includes an HTML table. The for-each element iterates over all the Guitar elements that are subelements of Guitars (note the XPath expression Guitar/Guitars defining the selection). Each iteration adds another row to the table, and the value-of elements initialize the table s cells with the values of the corresponding XML elements.

Converting XML to HTML on the Server

That s one way to convert XML to HTML. One drawback to this approach is that the XML document must contain a processing directive pointing to the style sheet. Another drawback is that the transformation is performed on the client. It doesn t work in IE 4 and probably won t work in most third-party browsers because XSLT wasn t standardized until recently. Unless you can control the browsers that your clients use, it behooves you to perform the transformation on the server where you can be sure an up-to-date XSLT processor is available.

How do you perform XSL transformations on the server? With XslTransform, of course. The Web page in Figure 13-18 Quotes.aspx demonstrates the mechanics. It contains no HTML; just a server-side script that generates HTML from an XML input document named Quotes.xml and a style sheet named Quotes.xsl. XslTransform.Transform performs the transformation. Its first parameter is an XPathDocument object wrapping the source document. The third parameter specifies the destination for the output, which in this example is the HTTP response. The second parameter, which is not used here, is an XsltArgumentList containing input arguments. Before calling XslTransform.Transform, Quotes.aspx calls another XslTransform method named Load to load the style sheet that governs the conversion. The resulting Web page is shown in Figure 13-17.

Figure 13-17

Output from Quotes.aspx.

Quotes.aspx

<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml.XPath" %> <%@ Import Namespace="System.Xml.Xsl" %> <% XPathDocument doc = new XPathDocument (Server.MapPath ("Quotes.xml")); XslTransform xsl = new XslTransform (); xsl.Load (Server.MapPath ("Quotes.xsl")); xsl.Transform (doc, null, Response.OutputStream); %>
Figure 13-18

Web page that converts XML to HTML on the server.

Quotes.xml

<?xml version="1.0"?> <Quotes> <Quote> <Text>Give me chastity and continence, but not yet.</Text> <Author>Saint Augustine</Author> </Quote> <Quote> <Text>The use of COBOL cripples the mind; its teaching should therefore be regarded as a criminal offense.</Text> <Author>Edsger Dijkstra</Author> </Quote> <Quote> <Text>C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg.</Text> <Author>Bjarne Stroustrup</Author> </Quote> <Quote> <Text>A programmer is a device for turning coffee into code.</Text> <Author>Jeff Prosise (with an assist from Paul Erdos)</Author> </Quote> <Quote> <Text>I have not failed. I&apos;ve just found 10,000 ways that won&apos;t work.</Text> <Author>Thomas Edison</Author> </Quote> <Quote> <Text>Blessed is the man who, having nothing to say, abstains from giving wordy evidence of the fact.</Text> <Author>George Eliot</Author> </Quote> <Quote> <Text>I think there is a world market for maybe five computers.</Text> <Author>Thomas Watson</Author> </Quote> <Quote> <Text>Computers in the future may weigh no more than 1.5 tons.</Text> <Author>Popular Mechanics</Author> </Quote> <Quote> <Text>I have traveled the length and breadth of this country and talked with the best people, and I can assure you that data processing is a fad that won&apos;t last out the year.</Text> <Author>Prentice-Hall business books editor</Author> </Quote> <Quote> <Text>640K ought to be enough for anybody.</Text> <Author>Bill Gates</Author> </Quote> </Quotes>

Quotes.xsl

<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <body> <h1 style="background-color: teal; color: white; font-size: 24pt; text-align: center; letter-spacing: 1.0em"> Famous Quotes </h1> <table border="1"> <tr style="font-size: 12pt; font-family: verdana; font-weight: bold"> <td style="text-align: center">Quote</td> <td style="text-align: center">Author</td> </tr> <xsl:for-each select="Quotes/Quote"> <xsl:sort select="Author" /> <tr style="font-size: 10pt; font-family: verdana"> <td><xsl:value-of select="Text"/></td> <td><i><xsl:value-of select="Author"/></i></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

As you might guess, there s much more to XSLT than these examples demonstrate. In addition to supporting for-each and value-of elements, for example, XSLT supports if and choose elements for conditional branching, variable elements for declaring variables, sort elements for sorting (look closely and you ll see sort used in Quotes.xsl), and a whole lot more. For a complete list of elements and a summary of XSLT s syntax, refer to the XSLT specification at http://www.w3.org/TR/xslt.

Converting XML Document Formats

To put an exclamation point at the end of this chapter, Figure 13-19 contains the source code for a simple application that transforms an XML document using the specified XSL style sheet and writes the results to the host console window. It s a handy tool for debugging style sheets by previewing their output. The following command lists the HTML that s generated when Quotes.xml is transformed with Quotes.xsl:

transform quotes.xml quotes.xsl

As you can see, the XslTransform class makes such a utility exceedingly easy to write just one more piece of evidence of how valuable and capable a tool the .NET Framework class library is for reading, writing, and manipulating XML documents.

Transform.cs

using System; using System.Xml.XPath; using System.Xml.Xsl; class MyApp { static void Main (string[] args) { if (args.Length < 2) { Console.WriteLine ("Syntax: TRANSFORM xmldoc xsldoc"); return; } try { XPathDocument doc = new XPathDocument (args[0]); XslTransform xsl = new XslTransform (); xsl.Load (args[1]); xsl.Transform (doc, null, Console.Out); } catch (Exception ex) { Console.WriteLine (ex.Message); } } }
Figure 13-19

Utility for previewing XSL transformations.



Programming Microsoft  .NET
Applied MicrosoftNET Framework Programming in Microsoft Visual BasicNET
ISBN: B000MUD834
EAN: N/A
Year: 2002
Pages: 101

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net