JavaScript Editor Free JavaScript Editor     JavaScript Debugger 

Main Page

Previous Page
Next Page

Chapter 10. XSLT

The movie Star Trek: The Wrath of Khan introduced a device called the Genesis Torpedo that rearranged matter on a subatomic level to produce life-bearing planets. Talk about your mad scientist stuff! eXtensible Stylesheet Language for Transformations (XSLT) is the XML equivalent to Star Trek's Genesis; it rearranges XML at the element level to produce the desired results. However, unlike Genesis, the desired results are not limited to a single type, but rather can be any conceivable XML or text-based format. In addition, instead of the original document being modified, a new document is created in the desired format, which could be identical to the original document or vastly different.

An XSLT document, sometimes referred to as a style sheet, is a well-formed XML document that uses the XSLT namespace (xmlns:xsl= to describe the rules for transforming the source XML document into the result XML document. XSLT is always used in conjunction with XPath, which specifies the location of various elements within the source document. XSLT, on the other hand, describes the structure of the result document.

Listing 10-1 contains a simple style sheet whose purpose is to simply copy the source XML document to the result XML document. Because no specific node names are used, this style sheet works equally well with all XML documents.

Listing 10-1. Simple Style Sheet to Copy the Source XML Document to the Result XML Document

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
      <xsl:output method="xml" version="1.0" encoding="UTF-8"/>
      <xsl:template match="/">

            <xsl:copy-of select="."/>



The XSL style sheet shown in Listing 10-1 works like this. First, the XML declaration describes the version of XML and the character set encoding. The xsl:stylesheet element describes the document as a style sheet, and the attributes specify the version of XSLT and the namespace. The xsl:output element defines the result document's XML declaration. The xsl:template defines a relationship between the source XML document and the result document. For example, the match attribute with the / specifies the source document's root node; all child elements of this element will be applied to the root element. Finally, the xsl:copy-of specifies to perform a deep copy of the context node; in other words, copy the context node and all descendants recursively.

This chapter covers the following topics:

Previous Page
Next Page

JavaScript Editor Free JavaScript Editor     JavaScript Debugger