X hits on this document





41 / 142

Transforming XML with XSLT

XSLT is a programming language in the form of an XML file. Therefore, each of the commands is an XML element, and commands are qualified using XML attributes. Here is a simple list of some of those commands:

  • stylesheet - This is the root of all XSLT files. It requires attributes defining the XSLT namespace and version number. This is pretty much the standard XSLT stylesheet definition: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">.

  • output - This is used to denote what type of text file will be created as output and whether or not it requires indentation and/or a DTD specification. For example, this use of output tells the XSLT pro- cessor to indent the output to make the resulting text easier to read: <xsl:output indent="yes" />.

  • template - This command is used to match/search for a particular part of an XML file. It requires an attribute named match and is used to denote what branch of the XML tree to process. For example, this use of template identifies all the things in the root element of the XML input file: <xsl:template match="/">.

  • value-of - Used to output the result of the required attribute named select which defines exactly what to output. In this example, the XSLT processor will output the value of a letter's date element: <xsl:value-of select="/letter/date/" />.

  • apply-templates - Searches the current XSLT file for a template named in the command's select statement or outputs the content of the current node of the XML file if there is no corresponding template. Here the apply-templates command tells the processor to find templates in the current XSLT file matching paragraph or list elements: <xsl:apply-templates select="paragraph | list" />.

  • Besides XSLT commands (elements), XSLT files can contain plain text and/or XML markup. When this plain text or markup is encountered, the XSLT processor is expected to simply output these val- ues. This is what allows us to create XHTML output. The processor reads an XML file as well as the XSLT file. As it reads the XSLT file it processes the XSLT commands or outputs the values of the non-XSLT commands resulting in another XML file or some other plain text file.

Exercise - Hello, World

In this exercise you will transform the simpliest of XML documents using XSLT.

Here is a very simple XML document:

<content>Hello, World!</content>

Our goal is to transform this document into a plain text output. To do that we will use this XSLT stylesheet:

<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<!-- plain o' text --> <xsl:output method='text'/>

<!-- match the root element -->


Document info
Document views501
Page views507
Page last viewedTue Jan 17 08:03:44 UTC 2017