XSL Transformations (XSLT), a W3C recommendation, is a language for transforming or changing XML documents into other XML documents that have very different data structures. This process is called
, in which the source XML data structure, called the
, is converted to the required output XML structure, called the
, by following the XSLT rules.
Graphically, the tree transformation appears as shown in Figure 6.1.
Figure 6.1. Tree transformation.
During the tree transformation process, the contents of the source tree can be reordered and filtered, and
-defined content and structure can be added to the result tree.
A transformation in the XSLT language is
as a well-
XML document that
the XML Namespaces recommendation. The XSLT document may include both elements that are defined by XSLT and elements not defined by XSLT. XSLT-defined elements are distinguished by
to a specific XML namespace defined in the URI http://www.w3.org/1999/XSL/Transform.
The document that contains the transformation is called a
. A stylesheet contains a set of template rules. A template rule has two
: a template that specifies what to do when the pattern is matched, and a pattern that is matched against nodes in the source tree. The output produced by the template forms a part of the result tree. This enables a stylesheet to be
to all documents that have similar source tree structures. A
a mechanism to identify or determine the existence of elements in a particular hierarchy or sequence. This addressing mechanism is defined by the XPath language. For example, consider the following source XML structure:
Suppose this XML document is to be transformed into the following XML structure:
To do this transformation, you would need to determine whether there is a carengine element under the carparts element, and if it exists, change it to an engine element. For a transformation such as this, the XSLT syntax would be as follows:
In an XSLT document, the set of rules that should be applied to the XML content that matches a specified pattern (written using XPath) is created using the template element.
In this example, the XPath syntax for determining the pattern of the carengine element under the carparts element is /carparts/carengine. XSLT, which is a
system, will select all the carengine elements under the carparts element.
When the element matching is done, you can transform it. Within the template, you have access to all the elements that fall under the matched element. To transform the elements, you can apply a template that has been defined
else in the XSLT document. This is done using the apply-template element. In our example, the template dictates that all occurrences of the carengine element under the carparts element must be transformed to an engine element.
Other than transforming XML documents into other XML documents, XSLT can also be used to transform an XML document into other formats, such as HTML, plain text, and even complex binary formats such as PDF.