Create xslt from xml. Creating reports based on xsl transformations (xslt). Now we need to finish the menu

brief information

Uses .NET 3.5 XML software to transform the metadata of an ArcGIS item or any XML file using an XSLT 1.0 style sheet and save the results to an XML file.

XSLT templates can be used to make a variety of changes to ArcGIS metadata or XML files. Some XSLT styles are provided in ArcGIS for Desktop. They can be found in the \Metadata\Stylesheets folder. These styles are described in the table below.

The following styles are used to create HTML documents that are used to display element information on the Description tab. They extract the metadata content of an object and add HTML formatting instructions to it. These styles import various XSLT templates from other files into the ArcGIS_Imports folder; Imported templates are used to perform most operations. If you are interested in creating custom styles display, more information about these styles can be found in the documentation provided with the ArcGIS Metadata Toolkit.

The following styles, contained in the \Metadata\Stylesheets\gpTools folder, take the element's metadata, process it, and save the resulting XML document into a new XML file. The purpose of this operation is to filter the item's metadata before it is used outside of ArcGIS. The purpose may also be to change the item's metadata. In this case, the resulting XML file can be saved back into the original element as the latter's metadata using the Metadata Importer tool. You can create a model or script that will first run the tool using the style to update the metadata content and then immediately save that content back into the element. The following styles are provided in ArcGIS for Desktop to perform some strictly defined metadata processing tasks.

add unique identifier.xslt

Abstract: Code generation by XSLT transformations is considered. The syntax of XSLT, the features of applying transformations, as well as performing operations such as filtering, sorting, and conditional selection in templates are studied. Performing transformation programmatically in C#. Advantages and disadvantages of technology.

XSLT Transformation Language

In the second lecture we already looked at an example using XSLT. In this lecture we will look at this technology in more detail. XSL (eXtensible Stylesheet Language) stands for Extensible Style Language, and is a language for creating styles for XML documents. XSLT(XSL Transformations) is the XSL transformation language and is part of it. The XSLT style is designed to transform the hierarchical structure and format of an XML document. The results of the conversion can be an XML file, a text file, program code, an HTML file, a PDF file, and so on. This language provides powerful capabilities for manipulating data, information, and text in a hierarchical form.

And this is exactly what is needed to generate code. Using XSLT can greatly help code generation. In addition, it provides a convenient alternative to T4 template technology.

XSLT was developed by a consortium W3C (World Wide Web Consortium). The first version of the language, XSLT 1.0, became a recommendation on November 16, 1999, and XSLT 2.0 became a recommendation on January 23, 2007. Both versions are used quite actively, and in this lecture we will look at the basic functionality that is common to them. This means that we will mainly consider the first version. We will also mention some commands from the second version.

How XSLT works

The XSLT model includes the following parts:

  • XML documents,
  • XSLT styles,
  • XSLT processor,
  • output documents.

XML Documents are input data that needs to be converted into other documents. Document XSLT style is a well formed XML document and contains a set of rules for performing the transformation. In other words, a style document is a template.

XSLT Processor is an application that accepts XML documents and XSLT styles as input. It performs transformation, that is, applying a set of rules in XSLT styles to XML documents. The result of this work is output documents.

XSLT processors have many implementations and are built into many browsers like Internet Explorer, Firefox, Mozilla, Opera and others. Internet Explorer uses the MSXML tool developed by Microsoft. XSLT processor is built into Internet Explorer starting from version 4.5. The generated output of the examples in this lecture can be viewed by opening the XML files in one of the browsers. At the end of the lecture, we will look at the possibilities of launching the transformation programmatically, using the appropriate programming language classes.

XPath

Another part of XSL technology is the language XPath, designed to access nodes in an XML document by specifying paths and expressions. The Xpath language is used in style files to navigate within XML documents, identifying parts of the source XML document that match one or more predefined patterns. When a match is found, the XSLT processor will apply the appropriate rules from the style file to it and transform it into part of the resulting document. XSLT style files make heavy use of XPath expressions.

Using XSLT

The XSLT language consists of many instructions written as tags. The name of each instruction usually begins with xsl characters. To perform the transformation, the XSLT style document must be a valid XML document.

To transform an XML document, you need to add a statement similar to the following at the beginning of the document:

An XSL stylesheet typically contains many elements, the most important of which is the xsl :stylesheet element. It is he who indicates that this XML file is a style file. In addition to it, it may contain other elements, for example xsl :template, xsl :value-of. The XML document and style file are passed to the XSLT processor, which processes these files, performs the transformation and outputs the result of the transformation.

Below is an XML document containing a list of programming languages.

C# Visual Basic Delphi Prolog Example 5.1.

Languages.xml file

You need to output this list in HTML format. For this purpose, we use the xsl :for-each instruction, which will apply part of the template to document sections whose names are specified in the select attribute. In our case, we will specify select="languages/language" .

The style file that will be used is:

My favorite languages: -

The template inside xsl :for-each outputs the contents of each language element from languages ​​. For this purpose, the xsl :value-of instruction and the select="." attribute are used. . This means that the processor must select the text content of the current element in the document. In addition to displaying content, you can specify the names of specific tags, as well as attributes to select the values ​​stored in them. Examples will be discussed below.

Let's open the XML file through Internet Explorer or another browser. The following text will be displayed:

My favorite languages:

  • Visual Basic
  • Delphi
  • Prolog

One of the most important elements in style is xsl:template. Serves to define a reusable template and contains the rules by which the XML document will be transformed. The match attribute contains an expression for selecting nodes to which the template will be applied. A name attribute may also be present. In this case, it is possible to call a template by name using the xsl :apply-templates instruction.

To repeat the template output for each document element, use the xsl :for-each statement. The pattern is executed for each element that matches the condition specified in the select attribute.

The xsl :value-of instruction is used to evaluate the expression written in the select attribute and then display the result in the place where the element itself is located.

Filtration

We considered the case where the values ​​of each node are read. However, there is often a need to select only part of the data, that is, they need to be filtered. XSLT templates support two filtering methods.

One is to use the select attribute of the xsl :for-each statement, and the second is to use the match attribute of the xsl :template element. We'll look at using match later, but for now we'll look at select .

Let's change the data file a little: add a high attribute, indicating whether the language from our list is a high-level language. We will also expand the list of languages.

C# Visual Basic Delphi Prolog Assembler Java Perl Example 5.3.

File languages4.xml

Note that the high attribute is set to false only for the "Assembler" value. Let's change the style sheet file a little:
High level languages: -

Example 5.4.

File languages4.xsl

In the [@ high ="true"] section we indicate that only those document nodes should be selected whose high attribute is set to "true" . The @ sign is a symbol indicating that it is followed by an attribute name.

  • Visual Basic
  • Delphi
  • Prolog

As you can see, the value "Assembler" is not displayed in the list of languages, that is, the XSLT processor filtered the data according to the specified conditions.

Sorting

In addition to filtering, another commonly used operation in code generation is sorting. The order-by attribute of the xsl :for-each instruction is used to sort the result, to indicate the order in which the document nodes are passed through when performing the transformation. The fields to be sorted are listed separated by semicolons and also have “+” or “-” signs in front of their names, indicating sorting in ascending or descending order.

Let's consider a slightly modified version of the document - instead of the high attribute, we will use the level element, which takes the values ​​high or low. And we will write the name of the language in the name element.

C# high Visual Basic high Delphi high Prolog high Assembler low Java high Perl high Example 5.5.

File languages6.xml

In the following style sheet for the xsl :for-each statement, we use the order-by attribute with the value +name , where the plus sign means to sort in ascending order.
High level languages: -

Example 5.6.



File languages6.xsl

In the select attribute, we filter by the value of the level element. Also in the select attribute of the statement

Chapter 1 XSLT Basics Welcome to the world of Extensible Stylesheet Language Transformations (XSLT). This book will serve as your guide to the vast world of XSLT, which is expanding in unpredictable ways every minute. We want this world to become your world too. There's a lot of ground to cover because XSLT is used in a lot of ways these days. interesting places and very

in interesting ways

. In this book you will see how it all works. XSLT itself is a means of processing and formatting the content of XML documents. XML has already become very popular, now it's XSLT's turn. XML gives you the ability to structure data in documents, and XSLT allows you to work with the content of XML documents - manipulate the content and create other documents (for example, when sorting XML employee database records or when saving data into an HTML document, as well as when formatting detailed data). you can perform similar types of tasks without programming. Instead of writing code to process the content of XML documents in Java, Visual Basic, or C++, you can simply use XSLT to specify what you want to do, and the XSLT processor will do the rest. This is exactly what XSLT is designed for, and it is emerging as a key player in the XML world.

XSL = XSLT + XSL-FO

XSLT itself is actually part of a larger specification, the Extensible Stylesheet Language, or XSL. XSL is designed to specify the precise, down to the millimeter, format of documents.

A much larger specification than XSLT, the formatting portion of XSL is based on special formatting objects—this portion of XSL is often called XSL-FO (or XSL:FO, or XSLFO). XSL-FO is a complex topic because styling documents using formatting objects can be a very confusing process. In fact, XSLT was originally added to XSL to make it easier to transform XML documents into documents based on XSL-FO formatting objects.

This book focuses on XSLT, but also covers an introduction to XSL-FO, including how to use XSLT to transform documents into XSL-FO form; after all, XSLT was first introduced to make working with XSL-FO easier. This chapter will begin with an overview of both XSLT and XSL-FO.

Brief historical background

XSL was created by the World Wide Web Consortium (W3C, www.w3.org), a coalition of groups originally led by Tim Berners-Lee. The W3C is the committee that produces specifications, such as the specification for XSL used in this book. Specifications are what make XML and XSL what they are.

The W3C originally developed the granddaddy of XML, SGML (Standard Generalized Markup Language), in the 1980s, but it was too complex to gain widespread popularity, and in reality XML (like HTML) represents is a simplified version of SGML. The W3C also created the Document Style Semantics and Specification Language (DSSSL) to work with SGML - and just as XML was derived from SGML, XSL is based on the original DSSSL. As the W3C states: “The model XSL uses for displaying documents on screen is based on many years of work on a complex ISO style language called Document Style Semantics and Specification Language (DSSSL).”

However, the original part of XSL, that is, XSL-FO, was still not simple enough to find widespread adoption, so XSLT was introduced as a means of making it easier to convert XML documents into XSL-FO form. As it turns out, XSLT was adopted because it is a complete transformation language that allows you to work with the content of XML documents without writing code, converting these documents into other XML documents, HTML, or other text-based formats. The great success of XSLT surprised even the W3C.

XSLT-XSL Transformations

XSLT allows you to work directly with the content of XML documents. For example, you might have a huge XML document containing all the baseball stats for the last season, but you might only be interested in the stats for pitchers. To extract just this data, you can write a program in Java, Visual Basic, or C++ that works with the XML parsers. Parsers are special software packages that read XML documents and pass all the document data sequentially into your code. Then you can create new document XML, pitchers.xml, containing only data about pitchers.

This method works, but it requires quite a lot of programming and spending a lot of time, including testing. XSLT was designed to solve problems like these. XSLT can be read by XSLT processors that process XML documents: all you need to do is create an XSLT style sheet that defines the rules you need to apply to transform one document into another. No programming is required, which is an undoubted advantage in the eyes of many people, even experienced programmers. In the baseball example, you would write an XSLT style sheet that defines the required actions and let the XSLT processor do the rest.

In addition to transforming one XML document into another XML document, you can also transform XML documents into different types of documents, such as HTML, rich text (RTF) documents, documents that use XSL-FO, and others. You can also transform XML documents into other XML-based languages ​​- such as MathML, MusicML, VML, XHTML and others - all without programming.

In many cases, XSLT can work similarly to a database language such as SQL (Structured Query Language). structured queries, - famous language Database Access) because it allows you to retrieve required data from XML documents in much the same way as an SQL statement retrieves data from a database. XSLT is sometimes even referred to as SQL on the Web, and if you're familiar with SQL, this will give you some insight into limitless possibilities XSLT. For example, using an XSLT style sheet, you can extract a subset of data from an XML document, create a table of contents for a large document, find all elements that meet a certain condition (for example, suppliers with a certain index), and so on. And all this - in one step!

XSL-FO: XSL Formatting Objects

Another part of XSL is XSL-FO, the formatting part of the XSL language, which we'll also be introduced to in this book. With XSL-FO, you can define how data is represented in XML documents, down to margin sizes, fonts, alignment, header and subheader sizes, and page width. There are a lot of things to think about when formatting an XML document, and as such, XSL-FO is significantly more extensive than XSLT.

On the other hand, due to its excessive complexity, XSL-FO is not very popular and cannot be compared to XSLT in this regard. There aren't many programs that support XSL-FO, and none of them come close enough to the standard. Just like the most common way to use XSLT is XML transformation In HTML, the most common use of XSL-FO is to convert XML to text in the Portable Data Format (PDF) format used in Adobe Acrobat. An example of such a conversion is given at the end of this chapter and also in Chapter 11.

W3C Specifications

The W3C produces specifications for both XML and XSL, and these are the ones we'll be working with throughout this book. W3C specifications are not called standards because, according to international agreements, standards can only be created by government-authorized committees. Instead, the W3C starts with a release requirements(requirements) for the new specification. The requirements are a list of goals and overviews of the specification, but the specification itself has not yet been written at this point. Next, the W3C releases specifications: first in the form work projects(working drafts), which can be commented on by all interested parties, then in the form recommendations for candidates(candidate recommendations), which are still subject to change; and finally, in the form of final recommendations(recommendations), which can no longer be changed.

The following list shows the XSLT-related W3C specifications that we will use in this book and where they can be found:

XSLT 1.1 working draft at www.w3.org/TR/xslt11. This is a working draft of XSLT 1.1 and will not be further developed prior to recommendation - the W3C plans to add all XSLT 1.1 functionality to XSLT 2.0;

XSLT 2.0 requirements at www.w3.org/TR/xslt20req. The W3C has released a group of targets for XSLT 2.0, including additional support for XML schemas;

XPath 1.0 specification at www.w3.org/TR/xpath. XPath is used to find and point to specific sections and elements in XML documents so that they can be manipulated;

XPath 2.0 requirements at www.w3.org/TR/xpath20req. XPath in this moment updated - additional support for XSLT 2.0 is added.

XSLT versions

The XSLT specifications have been developed much more actively than the specifications for all XSL. The XSLT 1.0 recommendation was finally adopted on November 16, 1999, and this version is the major version of XSLT today.

Then a working draft of XSLT 1.1 appeared and, although it was initially considered as a prologue new recommendation, a number of W3C staff began working on XSLT 2.0 - and after some time, the W3C decided to stop working on the XSLT 1.1 recommendation. This means that the XSLT 1.1 working draft will not be developed further - it will forever remain as a working draft and will never become a recommendation. In other words, there will be no official version 1.1 released for XSLT.

However, the W3C also states that it plans to incorporate much of what was done in the XSLT 1.1 working draft into XSLT 2.0, and so in this book I will briefly review the XSLT 1.1 working draft. I will be sure to mark material as "XSLT 1.1 Working Draft Only" when discussing new material introduced in the XSLT 1.1 Working Draft.

The following are the changes to XSLT 1.0 made in the XSLT 1.1 working draft; Please note that this list is provided here for reference only, as most of the material is unlikely to mean anything to you yet:

The result tree fragment data type supported in XSLT 1.0 has been removed;

The inference method can no longer arbitrarily add namespace nodes because the namespace setting process is applied automatically;

Support for XML Base has been added;

Multiple output documents are now supported using the element

;

Element

can now have parameters;

Extension functions can now be defined using the function

;

Extension functions can now return external objects that do not match any XPath data types.

This book discusses the XSLT 1.0 recommendation. and a working draft of XSLT 1.1. In furtherance of this topic, the W3C released requirements for XSLT 2.0, which are also discussed in the book under the name XSLT 2.0. The following list provides an overview of the goals of XSLT 2.0:

Add additional support for working with XML schema content using XSLT;

Simplify working with strings;

Simplify working with XSLT;

Improve support different languages;

Maintain increased processor efficiency.

Although XSLT 2.0 will not be released in its final form for some time, I will review what is known about it when discussing topics related to it. For example, the W3C's successor to HTML is the XML-based language XHTML. XSLT 1.0 and the XSLT 1.1 working draft do not directly support transformations from XML to XHTML, so we will have to create this transformation from scratch. However, such support is included in XSLT 2.0, and I will note this fact when discussing XHTML.

Thus, we have considered a brief overview of the topic; let's get to work. XSL is designed to work with XML documents, so first I want to look at the structure of XML documents. You'll be working with XML documents, but XSL stylesheets themselves are also XML documents, which is something to keep in mind when writing them. This book assumes that you have knowledge of both XML and HTML.

XML Documents

You should understand how XML documents work, so check this section to see if you're ready to get started. Let's look at an example XML document:

Here's how this document works: I started with an XML processing statement (all XML processing statements begin with ) meaning that it is used XML versions 1.0, the only version currently defined, and the character encoding is UTF-8, which is an eight-bit compressed version of Unicode:

Welcome to the wild and woolly world of XML.

Then I create new tag(tag) with name

. You can use any name for the tag, not necessarily DOCUMENT; All that is required is that the name must begin with a letter or underscore (_) and be followed by letters, numbers, underscores, periods (.), or hyphens (-), but not spaces. In XML, tags always begin with< и заканчиваются >.

XML documents are composed of XML elements; the latter begin with an opening tag such as

(followed by the element's content, if any, such as text or other elements), and ends with a closing tag paired with the opening tag (this begins with the characters Welcome to the wild and woolly world of XML

This book doesn't cover DTD declarations, but it does show that an element

- the root one, and the elements can, firstly, be located inside it, and secondly, contain text.

XML documents can contain all sorts of hierarchies, with one element nested within another element and so on through many levels of nesting. You can also assign attributes to elements, for example:

, where the attribute contains the value "". Using such attributes, it is convenient to store additional data about elements. It is also possible to include comments in XML documents that explain certain elements with text inside the and tags.

Below in Listing 1.1 is an example XML document

, which uses these capabilities to store data about the planets Mercury, Venus and Earth - such as mass, day length, density, distance from the Sun, etc. We'll work with this document throughout the book because it contains most of the XML features you'll need in a compact form. Listing 1.1. planets.xml .0553 58.65 1516 .983 43.4 .815 116.75 37l6 .943 66.8 1 2107 1 128.4

You also need to understand a number of XML definitions adopted in this book:

CDATA. Simple character data (that is, text that does not contain any markup);

ID. A valid XML name, which must be unique (that is, not used in any other ID type attributes);

IDREF. Contains the value of the ID attribute of some element, usually different from the element with which the current element is associated;

IDREFS. Multiple element identifiers (IDs), separated by spaces;

NAME Symbol . Letter, place, period, hyphen, underscore, or colon;

NAME. An XML name that must begin with a letter, underscore, or colon, possibly followed by additional name characters;

NAMES. A list of names separated by a delimiter character;

NMTOKEN. A token formed from one or more letters, numbers, hyphens, underscores, colons and periods;

NMTOKENS. Multiple valid XML names in a list, separated by a delimiter character;

NOTATION. Notation name (which must be declared in the DTD);

PCDATA. Parsed character data. PCDATA does not contain any markup, and any entity references have already been expanded in PCDATA.

We now have an understanding of XML documents, including what a well-formed and valid document is. If you don't feel confident enough with this material yet, read another book on the topic. You can also look at some XML resources on the Web:

http://www.w3c.org/xml. The World Wide Web Consortium's main XML Web site, the starting point for all things XML;

http://www.w3.org/XML/1999/XML-in-10-points, “XML in 10 steps” (actually only seven) - an overview of XML;

http://www.w3.org/TR/REC-xml. Official W3C Recommendation for XML 1.0, current (and only) version. Not too easy to read

http://www.w3.org/TR/xml-stylesheet/. All about how style sheets and XML work;

http://www.w3.org/TR/REC-xml-names/. All about XML namespaces;

http://www.w3.org/XML/Activity.html. Review of current XML activities at W3C;

Http://www.w3.org/TR/xmlschema-0/, http://www.w3.org/TR/xmlschema-1/ and http://www.w3.org/TR/xmlschema-2/ . XML Schemas, an alternative to DTD declarations;

http://www.w3.org/TR/xlink/. XLinks Specification;

http://www.w3.org/TR/xptr. XPointers Specification;

http://www.w3.org/TR/xhtml1/. XHTML 1.0 Specification;

http://www.w3.org/TR/xhtml11/. XHTML 1.1 Specification;

Http://www.w3.org/DOM/.W3C Document Object Model, DOM (Document Object Model).

Now we have learned how to create XML documents. What are they in visual form?

What does XML look like in a browser?

You can directly display XML documents using a browser such as Microsoft Internet Explorer version 5 or later. For example, if you save the XML document we created as greeting.xml and open it in Internet Explorer, it will look like the one shown in Figure. 1.1.

Rice. 1.1. XML document in Internet Explorer


In Fig. 1.1 you can see the entire XML document. There is no formatting, the XML document looks exactly the same in Internet Explorer as if you printed it. (To display the screen shown in Figure 1.1, Internet Explorer used its default style sheet. It converts XML into Dynamic HTML, which Internet Explorer can work with.) What if we want to present the data in a different way? Let's say we want to present the data from planets.xml in an HTML document as an HTML table?

This is where we need XSLT transformations. In this chapter we'll introduce them, and at the end of the chapter we'll look at the other side of XSL - XSL-FO.

XSLT transformations

XSLT has great capabilities for manipulating data in XML documents. For example, using an XSLT stylesheet, I could format data from

V HTML table. Style sheets contain rules set for transforming an XML document, and much of the book is devoted to creating style sheets and explaining how they work. Here's what an XSLT stylesheet looks like (Listing 1.2) that converts the data from planets.xml into an HTML table (we'll analyze it in Chapter 2). Listing 1.2. planets.xsl xmlns:xsl="http://www.w3.org/1999/XSL/Transform">



As you can see, this XSLT style sheet looks like an XML document - and for good reason, because it is. All XSLT style sheets are also XML documents, and if so, they must be well-formatted XML documents. With these two documents -

(Listing 1.1) and its associated stylesheet, (Listing 1.2) - we'll work throughout the book looking at the various possible XSLT transformations.

How do you link this style sheet to the XML document

? As we'll see in the next chapter, one way to do this is with an XML processing instruction that uses two attributes. The first attribute is , which should be set to "text/xml" to indicate that an XSLT stylesheet is being used. (To use another type of style sheet - cascading stylesheets (CSS), typically used with HTML - you should specify "text/css".) The second attribute is , which should be set to a URI (remember that XML does not use URLs , and URIs, Uniform Resource Identifier) ​​style sheets: .0553 58.65 1516 .983 43.4

Now with the help processor(processor) XSLT table can be applied

to and create a new document, . The XSLT processor creates a new file, which you can see in Fig. 1.2.

Rice. 1.2. HTML document generated by the XSLT processor


As can be seen in Fig. 1.2, the XSLT processor reads data from

, applies the rules from them and creates an HTML table in planets.html. This is our first example of an XSLT transformation.

What's really going on here? We had an XML document,

, and XSLT style sheet, . But how did they come together to create? What you need for XSLT transformation

To perform XSLT transformation such as transform

in , an XSLT processor is required. You can use XSLT in three ways to transform XML documents:

Using separate programs called XSLT processors. There are several programs that perform XSLT transformations, usually based in Java, some of which we'll look at in this chapter;

On the client side. A client program, such as a browser, can perform the conversion by reading the style sheet specified in the processing instruction

. In particular, Internet Explorer can perform this kind of transformation;

On the server side. A server program, such as a Java servlet, can transform the document automatically using a style sheet and send it to the client.

In this book, we'll look at all three ways to perform XSLT transformations. Already in this chapter an overview of all these three different methods will be provided.

Using separate XSLT processors

Separate XSLT processors are one of the most common ways to perform XSLT transformations. There are quite a lot of such processors, although not all of them can handle everything. possible tables XSLT styles. To use the XSLT processor, simply run it from the command line (in a DOS window on Windows), specify the name of the XML source document, the name of the style sheet to use, and the name of the document you want to create.

Below is a list of some XSLT processors available on the Internet in alphabetical order- most (but not all) of them are free:

4XSLT, http://Fourthought.com/4Suite/4XSLT. XSLT processor for Python;

EZ/X, http://www.activated.com/products/products.html. Java package for both XML parsing and XSLT processing;

iXSLT, http://www.infoteria.com/en/contents/download/index.html Command-line XSLT processor;

Koala XSL Engine, http://www.inria.fr/koala/XML/xslProcessor. An XSLT processor for Java that uses the Simple API for XML (SAX 1.0) and the Document Object Model (DOM 1.0) API;

LotusXSL, http://www.alphaworks.ibm.com/tech/LotusXSL. IBM's LotusXSL implements an XSLT processor in Java and can interface with APIs that conform to the Document Object Model (DOM) Level 1 Specification. The well-known XSLT processor, but now it is being replaced by Xalan 2.0;

MDC-XSL, http://mdc-xsl.sourceforge.net. XSLT processor in C++, it can be used as a separate program;

Microsoft XML Parser, http://msdn.microsoft.com/downloads/webtechnology/xml/msxml.asp. XML parser from Microsoft, high-performance, available as a COM component. It can be used to implement XSLT support in applications;

Sablotron, http://www.gingerall.com/charlie-bin/get/webGA/act/sablotron.act. Sablotron is a fast, compact and portable XSLT processor. Currently supports a subset of the XSLT recommendation. It can be used with C or Perl;

SAXON, http://users.iclway.co.uk/mhkay/saxon/index.html. This XSLT processor fully implements XSLT 1.0 and XPath 1.0, as well as a number of extensions to those specifications. Please note that this release also includes support for the XSLT 1.1 working draft;

Transformiix, http://www.mozilla.org. Transformiix is ​​an XSLT component from Mozilla, currently partially implemented in Netscape 6.0;

Unicorn XSLT processor (UXT), http://www.unicorn-enterprises.com. This XSLT processor supports XSLT transformations and is written in C++;

Xalan C++, http://xml.apache.org/xalan-c/index.html. Implementation of W3C recommendations for XSLT and XML Path Language (XPath). C++ version of the famous Apache Xalan processor;

Xalan Java, http://xml.apache.org/xalan-j/index.html. Implementing W3C recommendations for XSLT and XML Path Language (XPath) in Java. Java version of the famous Apache Xalan processor. Also includes extension functions for accessing SQL databases via JDBC and much more;

xesalt, http://www.inlogix.de/products.htmL This XSLT processor exists as a web server module (for both Apache and IIS web servers), as a Netscape 4.x extension, and as a processor command line;

XML parser for C, http://technet.oracle.com/tech/xml/parser_c2. XSLT processor from Oracle. Supports XSLT 1.0 recommendation, designed for use with C;

XML parser for Java, http://technet.oracle.com/tech/xml/parser_java2. XSLT processor from Oracle. Supports XSLT 1.0 recommendation, designed for use with Java;

XML parser for PL/SQL, http://technet.oracle.com/tech/xml/parser_plsql. XSLT processor from Oracle. Supports XSLT 1.0 recommendation, designed for use with PL/SQL;

XML:XSLT, http://xmlxslt.sourceforge.net. This XSLT parser is written in Perl. Partially implements the XSLT recommendation;

Xport, http://www.timelux.lu. XSLT transformation processor, available as a COM object;

XSL:P, http://www.clc-marketing.com/xslp/download.html. Modern XSLT processor;

XT, http://www.jclark.com/xml/xt.html. XT is a well-known implementation of the XSLT recommendation in Java.

In the following sections, we'll take a closer look at four of the XSLT processors listed above: XT, Saxon, Oracle's XSLT processor, and Xalan. They are all available for free on the Internet and can be used to test all the examples in the book. If you want to study examples, download one of these processors (the best known and widely used is the Xalan processor). To implement XSLT transformations, I will use these processors in the following discussion.

The selected processors are Java based and require you to have Java installed. If you don't already have it installed, you can download it for free from Sun's website. The most recent edition, at the time of writing, Java 2 version 1.3 is available at http://java.sun.com/j2se/1.3. All you need to do is download Java for your operating system and follow the download instructions on the appropriate pages.

While these XSLT processors require Java to run, there's no need to worry if you're not a programmer—no programming is required. Chapter 10 will include Java programming examples to show you how to create XSLT transforms in code, but XT, Saxon, Oracle's XSLT, and Xalan processors can all be run from the command line.

If you're on Windows, there's an even easier way to use XT and Saxon - these processors come as .exe files (

and ), which can be done directly on Windows - and you won't need Java at all. This way of working is also discussed in the book. Using the XSLT Processor in Java

To work with the Java-based XSLT processor, simply download and unzip it and it's ready to go. Read the accompanying instructions, of course; but, as a rule, only two steps need to be carried out.

First, you need to tell Java how to find the XSLT processor, which is stored in a Java Archive file, or JAR. To tell Java where to look for a JAR file, you need to set the classpath environment variable to the path of that JAR file. For example, on any version of Windows, you would open a DOS window and run a command that sets the classpath variable to the path to the Oracle XSLT processor JAR file, xmlparserv2.jar, which in this case is stored in the directory

:

Now you can move on to the second stage - launch the XSLT processor; this will execute the Java class that supports the processor. For the Oracle XSLT processor, this class is called

. On Windows, for example, you can go to the directory where the and files are located, and execute the class using Java like this: C:\planets>

In this case the file

will be converted to using . Note that this example assumes that the java.exe file, which runs the Java code, is located in your Windows directory. If it is not there, you can explicitly specify its location, the Java bin directory, for example (JDK is short for Java Development Kit, and Java 2 version 1.3 installs itself by default in the directory), as in the following command: C:\planets>c: \jdk1.3\bin\java oracle.xml.parser.v2.oraxsl planets.xmlplanets.xslplanets.html

You can combine both stages (setting the variable

and starting the XSLT processor) into one if you use the key along with Java, specifying which variable to use: C:\planets>c:\jdk1.3\bin\java -cf c:\oraclexml\lib\xmlparserv2.jar oracle .xml.parser.v2.oraxsl planets.xml planets.xsl planets.html

These are quite long commands, which may seem overly complicated at first glance. However, there is a good reason why most XSLT processors are written in Java: Java is supported on many platforms, from Macintosh to UNIX, and therefore an XSLT processor can also run on all of these platforms.

Of course, things get a lot easier if you're on Windows and using the compiled version of the XT processor (

) or Saxon(). Below is an example on Windows to accomplish the same conversion (assuming it's located in the current directory): C:\planets>

We've covered the process briefly; Now I want to describe the four XSLT processors (XT, Saxon, Oracle's XSLT processor, and Xalan) in detail, demonstrating how to work with each of them. Please note two things: software that implements XML and XSL changes very quickly, so by the time you read this, some processors may already be outdated; Although all processors should support all standard XSLT, in some cases they produce different results.

XT James Clark

XT by James Clark can be downloaded from www.jclark.com/xml/xt.html. In addition to the XT processor itself, you will need an XML parser that will allow the XT to read your XML document. There is also a file in the XT download files

, containing James Clark's XML parser; You can, however, use its XP parser for the same purposes by downloading it from the address www.jclark.com/xml/xp/index.html.

My personal preference is to use the Xerces XML parser from the Apache Project, which is located at http://xml.apache.org. (By the time the book was written current version, Xerces 1.3.0, could be downloaded from http://xml.apache.org/dist/xerces-j/ at zip format for UNIX in a file

and Windows format in the file.)

The XT Processor itself is a Java application included in the XT download package. JAR file,

. To use and, you must include both files in the variable, as shown in the following example for Windows (change the locations of these files accordingly): C:\>set classpath=C:\xerces-1_3_0\xerces.jar;C :\xt\xt.jar

Then you can use the XT transform class,

com.jclark.xsl.sax.Driver.class. You need to provide the name of the parser you want to use (in this case, org.apache.xerces.parsers.SAXParser in the archive) by setting a variable to the desired name on the command line. Here's how I use XT to do the conversion on Windows (assuming the files are contained in a directory and are located in your current directory): C:\planets>java -Dcom.jclark.xsl.sax.parser=org.apache.xerces. parsers.SAXParser com.jclark.xsl.sax.Driver planets.xml planets.xsl planets.html

This line is quite long and the good thing is that XT is also packaged into a Win32 executable

. To work with, however, it is necessary that the Java virtual machine from Microsoft is installed on your computer, Microsoft Java Virtual Machine (VM) - it is included with Internet Explorer. Here is an example on Windows that does the same conversion as the previous line (assuming it is located in the current directory): C:\planets>xt planets.xml planets.xsl planets.html is not located in the current directory, you can specify its location explicitly, as in the following example (if located in ): C:\planets>c:\xt\xt planets.xml planets.xsl planets.html Saxon

Michael Kay's Saxon is one of the very first XSLT processors and can be downloaded for free from http://users.iclway.co.uk/mhkay/saxon/. All you need to do is download the saxon.zip file and extract the zip archive; the required Java JAR file will be created,

.

To perform an XSLT transformation, you first need to make sure that

is in the variable. For example, on Windows, assuming that it is in , you can set the variable as follows: C:\>set classpath=c:\saxon\saxon.jar

You can now use the Saxon XSLT class to perform the transformation,

com.icl.saxon.StyleSheet.class : C:\planets>java com.icl.saxon.StyleSheet planets.xml planets.xsl

By default, Saxon prints the results to the screen - not exactly what we want if we want to create a file

. To create a file, you can use the UNIX or DOS output redirection symbol >: C:\planets>java com.icl.saxon.StyleSheet planets.xml planets.xsl > planets.html

When running on Windows, it's easy to immediately invoke Saxon in the form of the Win32 executable, saxon.exe, which can be downloaded from http://users.iclway.co.uk/mhkay/saxon/. On Windows it can be launched as follows (part

specifies the output file name): C:\planets>saxon -o planets.html planets.xml planets.xsl Oracle XSLT

Oracle Corporation also provides free processor XSLT, which can be downloaded from http://technet.oracle.com/tech/xml/, although this will require a very lengthy registration procedure. At the time of writing, downloading the XSLT processor was as easy as clicking on the link for the XDK for Java at http://technet.oracle.com/tech/xml/.

After extracting the zip archive downloaded from the Oracle website, the required JAR file (at the time of writing) will be called

. It can be placed in your variable on Windows like this: C:\>set classpath=c:\oraclexml\lib\xmlparserv2.jar

Required Java class -

, to convert to you can use it this way: C:\planets>java oracle.xml.parser.v2.oraxsl planets.xml planets.xsl planets.html Xalan

Probably the most widely used single XSLT processor is the Apache Project's Xalan (Apache is a widely used web server). The Java version of Xalan can be downloaded from http://xml.apache.org/xalan-j/index.html - just click on the zip archive file you require (currently

for Windows or for UNIX).

When you unzip the downloaded file you will receive both XSLT processor,

, and the XML parser, . Both of these JAR files can be included in Windows as follows (change the file paths to suit your system): C:\>set classpath=c:\xalan-j_2_0_0\bin\xalan.jar;c:\xalan-j_2_0_0 \bin\xerces.jar

To then use

to convert to , run the Java class: C:\planets>java org.apache.xalan.xslt.Process -IN planets.xml -XSL planets.xsl -OUT planets.html

Note that the input file is specified using

, to indicate the output - , and to indicate the XSLT style sheet - . We'll be working with the Xalan processor most often, so more details are provided below. The following list contains all the tokens that can be used with the class, as output by Xalan itself: . Use only carriage return characters in the output - CR/LF is used by default; . Time diagnostic output; . Copy stack on error; . Use HTML format; ; . The number of spaces to align (indent) each level in the output tree is 0 by default; . Use only linefeed characters in the output - CR/LF is used by default; ; . Sets the stylesheet option; . Mode with minimal output (quiet); . Quiet Pattern Conflicts Warnings, warnings of pattern conflicts; . Use Formatter plain text; . Track each event of generating the result tree; . Track each allocation event; . Track templates as they are called; . Track the “children” of the template as they are processed; . Version information; . Validate input XML and XSL (validation is disabled by default); . Use XML formatters and add an XML header; .

We'll look at all of these processors in the book; As mentioned, I will be using Xalan most often. (The reason is that it has become the most popular and widely adopted XSLT processor.) Of course, you can use any XSLT processor as long as it meets the W3C XSLT specification.

This concludes our discussion of individual XSLT processors. There is another way to transform XML documents without resorting to separate program: For these purposes, you can use a client program such as a browser.

Converting XML Documents Using Browsers

XSLT support is included in both Microsoft Internet Explorer and Netscape Navigator. Of the two browsers, Internet Explorer has much more XSLT support, and I'll be using version 5.5 of that browser here. You can read about XSLT support in Internet Explorer at http://msdn.microsoft.com/xml/XSLGuide/.

Internet Explorer 5.5 and earlier does not support exactly XSLT syntax by default, so we need to make a number of modifications to the files

And . (We'll look at this topic in more detail in the next chapter. There are addresses where you can download updated XSLT support packages.) Internet Explorer 6.0 was already available when this book was going to press. I installed it and checked its operation; It appears to support standard XSLT syntax (except that it is still required to use the type "" for style sheets - such as instead of ""). If you are still using IE 5.5 or earlier, you will need to make the changes listed here and in the next chapter. If you want to avoid this, use IE 6.0: this browser seems to support full XSLT syntax.

To work with

In IE (including version 6.0), I had to convert the attribute in the processing instructions from "" to "" (assuming the file is located in the same directory as , as the attribute in Listing 1.3 indicates). Listing 1.3. Version of planets.xml for Microsoft Internet Explorer Mercury .0553 58.65 1516 .983 43.4 .815 116.75 3716 .943 66.8 1 2107 1 128.4

Now if you are using IE version 5.5 or earlier you should also convert the stylesheet

(but not for version 6.0 and older; in this case, you only need to change the type attribute in the processing instruction from "" to ""). We'll look at how to do this in the next chapter, but here's the new version of planets.xsl to use: Listing 1.4. Version of planets.xsl for Microsoft Internet Explorer




Now you can directly open planets.xml in Internet Explorer, as seen in Fig. 1.3.

Rice. 1.3. Performing XSLT transformation in Internet Explorer


Although in this way Internet help Explorer can work with XSLT, but you need to modify the style sheet so that it suits Internet requirements Explorer. Because Internet Explorer doesn't currently actually support XSLT by opening XML documents during navigation, I won't be using that browser for XSLT transformations in the book (except where specifically noted). I'll use XSLT processors like Saxon and Xalan to perform the transformations, and if the results are in HTML format, we'll view them in Internet Explorer.

It's interesting to note that there is a way to perform true XSLT transformations in Internet Explorer without making any special changes to the XML or XSL documents, without even downloading and installing the latest MSXML parser (as discussed in Chapter 2) - however, this requires no navigation XML document, and access Internet Explorer's built-in XSLT processor, MSXML3, directly using JavaScript.

Working with XSLT and JavaScript in Internet Explorer

The XSLT processor in Internet Explorer 5.5 is part of the MSXML3 XML parser, and if you work directly with MSXML3 using JavaScript, there is no need to modify the source files

and (Listings 1.1 and 1.2), as we did in the previous section. We'll see how this works in Chapter 10, but here's a web page that uses JavaScript and MSXML3 to perform the conversion using and display the results (note that you can modify this document to use your own XML and XSLT documents without having to to writing code in JavaScript: just replace the names with the names of your XML and XSL documents) (Listing 1.5). Listing 1.5. Conversion to Internet Explorer using JavaScript XSLT Using JavaScript var XMLDocument = new ActiveXObject("MSXML2.DOMDocument.3.0");

var XSLDocument = new ActiveXObject("MSXML2.DOMDocument.3.0");

var HTMLtarget = document.all["targetDIV"];

XMLDocument.validateOnParse = true;

XMLDocument.load("planets.xml");

if (XMLDocument.parseError.errorCode != 0) ( HTMLtarget.InnerHTML = "Error!"; XSLDocument.validateOnParse = true; XSLDocument.load("planets.xsl"); if (XSLDocument.parseError.errorCode != 0) ( HTMLtarget.innerHTML = "Error!"; HTMLtarget.innerHTML = XMLDocument.transformNode(XSLDocument);

You can perform XSLT transformations on the web server so that the XML document is transformed before the web server sends it to the browser. The most common transformation here is to convert an XML document to HTML, but server-side XML-to-XML transformations are also becoming more and more common.

Unlike the other XSLT transformations discussed so far in this chapter, running XSLT transformations on a Web server usually requires some programming. There are three common ways to perform XSLT transformations on web servers: using Java servlets, Java Server Pages (JSP), and Active Server Pages (ASP). In Chapter 10 we explore all three of these methods in detail. Several XSLT processors can be configured for use on web servers - here's a starting list:

AXSL, www.javalobby.org/axsl.html. AXSL is a server-side tool that converts XML to HTML using XSLT;

Microsoft XML Parser, http://msdn.microsoft.com/downloads/webtechnology/xml/msxml.asp. MSXML3 provides secure server access via HTTP for working with ASP;

mod_xslt, http://modxslt.userworld.com. A simple Apache web server module that uses XSLT to retrieve XML content. XSLT processing uses the Sablotron processor;

PXSLServlet, www.pault.com/Pxsl This servlet can be used to transform XML to HTML using XSLT. It also allows you to read and write data to a SQL-based database (via JDBC);

xesalt, www.inlogix.de/products.html. This XSLT processor exists as a module for the Apache and IIS web servers;

XML Enabler, www.alphaworks.ibm.com/tech/xmlenabler. XML Enabler allows you to send requests to a servlet, and when the servlet responds, XML Enabler can format the data using various XSLT style sheets;

XT, can be used as a Java servlet. It requires a servlet engine that implements at least version 2.1 of the Java Servlet API. The Java servlet class is called com.jclark.xsi.sax.XSLServlet.

The following example shows a JSP page that enables the Xalan processor on a web server. Xalan converts

using a style sheet. The code then reads the file and sends it back from the web server to the browser: XSLTProcessor processor = XSLTProcessorFactory.getProcessor();

processor.process(new XSLTInputSource("planets.xml"), new XSLTInputSource("planets.xsl"), new XSLTResultTarget("planets.html")); FileReader filereader = new FileReader("planets.html"); BufferedReader bufferedreader = new BufferedReader(filereader);

while((instring = bufferedreader.readLine()) != null) ( %>


The result can be seen in Fig. 1.4: This shows the planets.html file sent to Internet Explorer by the web server running the JSP. Chapter 10 provides

Additional Information

about using Java, JSP, and ASP servlets for server-side XSLT transformations.

Rice. 1.4. Converting XML on a web server

We looked at how to perform XSLT transformations using separate XSLT processors in Internet Explorer and web servers. However, the only conversion we have done so far is the XML to HTML conversion. Although it is now the most popular transformation, XML to XML transformations are also becoming more common.

XML to XML Conversions

XML-to-XML transformations are sometimes thought of as SQL for the web because they allow database queries to be run on XML documents. Below is an example. The file we use

contains quite a lot of data about each planet: .0553 58.65 1516 .983 43.4 .815 116.75 3716 .943 66.8



to using Xalan to create a new XML document, : C:\planets>java org.apache.xalan.xslt.Process -IN planets.xml -XSL planets.xsl -OUT new.xml

This is what the resulting XML document looks like,

: .0553(Earth = 1)

Note that this file looks very similar to the original file

, except that each element contains only the elements and . This way we were able to obtain a subset of the original XML document data.

Of course, any number of these kinds of XML-XML transformations can be performed. You can manipulate the data in an XML document to create entirely new XML documents. For example, you can take an XML document containing student names and grades and create a new document that displays grade averages. XSLT has many built-in functions that allow you to work with data in this way, which we'll look at in Chapter 8.

In addition, many programs use XML to exchange data on the Internet, and since they typically format their XML documents differently, another popular way to use XML-to-XML transformations on the Internet is to convert XML from a format used by one program , into the format of another program.

Conversions from XML to XHTML

While many books focus exclusively on XML to HTML conversions, the truth is that the W3C is not very happy about this. The consortium was trying to shift the focus from HTML (which they originally standardized) to their new specification, XHTML, which was an XML-compatible rewrite of HTML. XHTML documents are also well-formed valid XML documents, so a conversion from XML to XHTML is really a conversion from XML to a special kind of XML.

Although the W3C is actively promoting XHTML, the format has not yet become widespread. Therefore, in this book I mainly cover HTML; but since the W3C says that XHTML should be used, I'll cover the topic briefly here and in Chapter 6. If you want to learn more about XHTML, read the W3C XHTML 1.0 recommendation at www.w3.org/TR/xhtml1/, as well as the XHTML 1.1 at www.w3.org/TR/xhtml11/.

While the W3C says that XML should be converted to XHTML rather than HTML, I haven't seen a single working example on their website. The examples they provide do not actually generate valid XHTML documents. However, support for XML-XHTML transformations is expected to be built into XSLT 2.0, and the W3C's desired phenomenon is likely to be upon us soon.

We'll look at this type of conversion in more detail in Chapter 6, but here I'll give working version tables

, which produces a valid XHTML version (Listing 1.7). Note that this time you must use the attribute on the element, and although this is valid XSLT code, not all XSLT processors will be able to process it. Listing 1.7. XML-XHTML transformation xmlns:xsl="http://www.w3.org/1999/XSL/Transform">doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional .dtd" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" indent="yes"/>




I'll convert

into a valid XHTML document, using this new variant and the XSLT XT processor. First you need to set the variable correctly: С:\>set classpath=c:xerces\xerces-1_3_0\xerces.jar;с:\xt\xt.jar;

Then I do the conversion:

C:\planets>java -Dcom.jclark.xsl.sax.parser=org.apache.xerces.parsers.SAXParser.com.jclark xsl.sax.Driver planets.xml planets.xsl planets.html

The result will be an XHTML file,

:

This document,

, is indeed a well-formed and valid XHTML 1.0 document (the most popular form of XHTML) according to the W3C HTML and XHTML Validation Program. The HTML/XHTML Validator can be found on the Internet at http://validator.w3.org/file-upload.html. Chapter 6 provides more information about XML-XHTML transformations.

So far, we've given an overview of how XSLT works, looking at transformations from XML to HTML, XML, and XHTML. Later in the book, we'll look at XSLT transformations such as XML to RTF (Rich Text Format), plain text, XSL-FO, JavaScript, SQL-based databases, and more. There's also a lot of additional material on XSLT that you should know about, and now we'll get comfortable with the different kinds of XSLT resources that can be found on the Internet.

XSLT Resources

You can find a huge amount of information we need on the Internet. Please note that all URLs listed below are subject to change; the lists will be relevant for as long as the people who support the listed web sites want it.

XSLT Specifications, Guides, and Examples

The starting point for XSLT resources is, of course, the W3C itself. Below are the URLs for the W3C specifications used in the book:

www.w3.org/Style/XSL/. W3C main page on XSL;

www.w3.org/TR/xslt. XSLT Specification 1.0;

www.w3.org/TR/xslt11. Working draft XSLT 1.1, which simplifies working with XSLT extensions and adds support for the W3C XBase recommendation;

www.w3.org/TR/xslt20req. XSLT 2.0 Requirements, which provides an overview of XSLT 2.0 including additional support for XML schemas;

www.w3.org/TR/xsl/. XSL formatting objects;

www.w3.org/Style/2000/xsl-charter.html. XSL Committee Goals;

www.w3.org/TR/xpath20req. XPath Requirements, which provides an overview of XPath 2.0, which includes additional support for XSLT 2.0;

Http://lists.w3.org/Archives/Public/www-xml-stylesheet-comments/. List of W3C XML style sheets.

Many XSLT tutorials and examples are available from other sources as well - here's a starting list:

Http://http.cs.berkeley.edu/~wilensky/CS294/xsl-examples.html. A number of examples on XSLT;

http://msdn.microsoft.com/xml/reference/xsl/Examples.asp. Examples of XSLT templates used in matched elements;

http://msdn.microsoft.com/xml/XSLGuide/xsl-overview.asp. An initial description of working with XSLT;

www.lists.ic.ac.uk/hypermail/xml-dev/xml-dev-Nov-1999/0371.html. XSLT Guide as a PowerPoint Presentation;

www.mulberrytech.com/xsl/xsl-list/. An open list dedicated to discussion of XSL;

www.nwalsh.com/docs/tutorials/xsl/xsl/slides.html. XSLT Guide;

www.oasis-open.org/cover/xsl.html. Description of current events around XSLT;

www.w3.org/Style/Activity. An impressive list of pages dedicated to W3C style sheets;

www.xml101.com/xsl/. A complete set of XSLT references;

www.xslinfo.com. A useful set of XSLT resources compiled by James Tauber;

www.zvon.org/xxl/XSLTutorial/Books/Bookl/bookInOne.html. References for XSLT, XPath, XML, WML and other languages.

I am aware of only one Usenet newsgroup on XSLT, however, and it is maintained by Microsoft - microsoft.public.xsl. Over time, others will appear. You may also be interested in the list mailing list via XSL - www.mulberrytech.com/xsl/xsl-list.

In addition to the W3C specifications, guides, and examples, there are a large number of XSLT stylesheet editors available on the Internet.

XSLT editors

A standard text editor such as vi, emacs, pico, Windows Notepad, or Windows WordPad is sufficient to create the XML and XSL documents used in this book. By default, XML and XSL documents are expected to be written in Unicode, although in practice they can be written in ASCII, and virtually all documents to date have been written in ASCII. Just make sure that when you create a document, you save it in your editor's plain text format.

WORKING WITH WORDPAD

Windows text editors such as WordPad have an annoying feature - if they don't recognize the extension you give to a file, they append the .txt extension to the file name. For .xml and .xsl files this is not a problem because WordPad understands these extensions, but if you try to save documents created while working on a book with an extension that WordPad does not recognize, the editor will add the .txt extension to all of them. To prevent this from happening, when saving the document, enclose the file name in quotation marks: "file.abc".

It will, however, be much easier to use a real XML editor specifically designed for processing XML documents. Here is a list of XML document editing programs:

Adobe FrameMaker, www.adobe.com. Adobe introduces the excellent but expensive FrameMaker editor with XML support;

XML Pro, www.vervet.com/. Expensive but powerful XML editor;

XML Writer, on disk, XMLWriter http://xmlwriter.net/. Selection keywords color, user-friendly interface;

XML Notepad, msdn.microsoft.com/xml/notepad/intro.asp. Free editor XML from Microsoft, a little awkward to work with;

eNotepad, www.edisys.com/Products/eNotepad/enotepad.asp. An analogue of WordPad, which has good means work with XML and convenient user interface;

XMetal from SoftQuad, www.xmetal.com. An expensive but very powerful XML editor, the favorite editor of many authors;

XML Spy, www.xmlspy.com/. Has a good user interface and is easy to use;

Arbortext's Epic, www.arbortext.com/. A powerful editor, dear, with rich customization options.

The XML Spy editor is shown in Fig. 1.5, XML Writer - in Fig. 1.6, and XML Notepad - in Fig. 1.7.


Rice. 1.5. Editing XML in XML Spy



Rice. 1.6. Editing XML in XML Writer



Rice. 1.7. Editing XML in XML Notepad


There are also special XSLT editors. Here's a starting list:

Http://lists.w3.org/Archives/Public/xsl-editors/. XSL editor discussion list on the W3C website;

IBM XSL Editor, www.alphaworks.ibm.com/tech/xsleditor. An XSLT stylesheet editor in Java that provides a visual interface for writing stylesheets and selection and matching expressions. However, Java 2 version 1.1 (not 1.2 or 1.3) support must be installed;

Stylus, www.exceloncorp.com/products/excelon_stylus.html. Stylus includes an XSLT stylesheet editor;

Visual XML Transformation Tool, www.alphaworks.ibm.com/aw.nsf/techmain/visualxmltools. The Visual XML Transformation Tool generates XSLT for you to transform source documents into output documents;

Whitehill Composer, www.whitehill.com/products/prod4.html. WYSIWYG drag-and-drop XSLT stylesheet generator;

XL-Styler, www.seeburger.de/xml. Includes keyword highlighting, tag completion, preview HTML and much more;

XML Cooktop, http://xmleverywhere.com/cooktop/. This editor has just been released and looks decent. Includes tools for developing and validating XSLT style sheets;

XML Spy, www.xmlspy.com/. With this XML editor you can also edit XSLT;

XML Style Wizard, www.infoteria.com/en/contents/download. A tool that generates XSLT files using a wizard that examines the XML data and asks questions to the user;

xslide, www.mulberrytech.com/xsl/xslide. Supports XSLT editing mode for Emacs;

XSpLit, www.percussion.com/xmlzone/technology.htm. Allows you to share HTML documents on XML DTD definitions and XSLT style sheets.

XSLT Utilities

There are also many XSLT utilities on the Internet - the following list highlights the most famous:

Microsoft XSL API Extension, http://msdn.microsoft.com/downloads/webtechnology/xml/xslisapi.asp. Simplifies the task of performing XSLT transformations on the server side;

Microsoft XSL-to-XSLT Converter, http://msdn.microsoft.com/downloads/webtechnology/xml/xsltconv.asp. Converts XSL to XSLT;

XSL Lint, www.nwalsh.com/xsl/xslint. XSL Lint checks XSLT syntax, allowing you to detect many types of errors;

XSL Trace, www.alphaworks.ibm.com/tech/xsltrace. This product allows the user to walk through the steps of XSLT visually;

XSLT Compiler, www.sun.com/xml/developers/xsltc. Converts XSLT files into Java classes for converting XML files;

XSLT test tool, www.netcrucible.com/xslt/xslt-tool.htm. This tool gives you the ability to run XSLT on a variety of popular processors, allowing you to test whether your transformation works correctly on all systems. It is possible to call Microsoft's MSXML3 from the command line, just like any other XSLT processor;

XSLTC, www3.cybercities.com/x/xsltc. Compiles XSLT style sheets into C++ code. Based on Transformix, Mozilla's XSLT processor;

XSLTracer, www.zvon.org/xxl/XSLTracer/Output/introduction.html. XSLTracer is a Perl tool that demonstrates how to process XML files using XSLT style sheets.

This concludes the overview of XSLT in this chapter. As you can see, a huge set of information awaits us. The remainder of the chapter will provide an overview of XSL-FO.

XSL Formatting Objects: XSL-FO

The most popular part of XSL is XSLT transformations, which we already introduced in this chapter. Another, significantly larger part is XSL formatting objects, XSL-FO (XSL Formatting Objects).

With XSL-FO, you can specify the formatting and display of an XML document with millimeter precision. You can set anything you want for documents: text font, location, alignment, color, indexes, margin size, and much more. Working with XSL-FO is similar to the process of creating a word processor by hand, and due to the complexity of XSL-FO, some avoid using them. In Chapters 11 and 12, we'll explore what XSL-FO has to offer and how to work with it.

XSL-FO Resources

A number of XSL-FO resources are available on the Internet, but there are far fewer of them than XSLT resources. Here are the main ones:

Http://lists.w3.org/Archives/Public/www-xsl-fo/. List of W3C notes for XSL-FO.

Just as there are XSLT processors, there are also XSL-FO processors. None of them, however, come close to fully implementing the standard. Here is the initial list of XSL-FO processors:

FOP, http://xml.apache.org/fop. A Java application that reads the XSL formatting object tree (produced by the XML parser) and produces a PDF document;

PassiveTeX, http://users.ox.ac.uk/~rahtz/passivetex. A TeX package that formats XSL-FO output to PDF. Uses David Carlisle's xmltex XML parser;

SAXESS Wave, http://www.saxess.com/wave/index.html. XML-Shockwave/Flash Converter;

TeXML, http://www.alphaworks.ibm.com/tech/texml. Converts XML documents to TeX format;

Unicorn Formatting Objects (UFO), http://www.unicorn-enterprises.com. An XSL formatting object processor written in C++. Can generate output in PostScript, PDF and other formats supported by DVI TeX drivers;

XEP, http://www.renderx.com/F02PDF.html. An XSL-FO processor in Java that converts XSL formatting objects to PDF or PostScript.

In this book, I'll use the FOP (formatting objects processor), which is probably the most common XSL-FO processor. The Java-based XSL-FO processor takes an XML document written to use XSL-FO formatting objects and converts it into a PDF format that can be viewed in Adobe Acrobat. Although XSLT transformations are often done in HTML, this will not work for XSL-FO because it specifies every aspect of the document's presentation format down to the smallest details, and the PDF format is much better suited for these purposes.

Formatting an XML Document

For formatting

We can use the XSL-FO formatting objects introduced in Chapter 12. For example, here's how we can display the name of the first planet, Mercury, using the XSL-FO formatting objects and :

However, creating an entire document using XSL formatting objects is not an easy task, except for short documents. The W3C anticipated these difficulties, which is one of the main reasons the consortium introduced the transformation language, XSLT. Specifically, you can create a style sheet and use XSLT to transform the XML document so that it uses XSL formatting objects.

In practice, transformations are almost always done using style sheets, and that's what we'll do in Chapters 11 and 12. All you need to do is provide an XSLT style sheet that can be used to transform your document using formatting objects. With this method, the XSLT processor does all the work, transforming the document from a representation you're comfortable working with into a representation with formatting objects, which you can then paste into a program that can process the formatting objects and display the formatted result.

To clarify all of the above, below is an example of working with an XML document that we have already encountered in this chapter,

: .0553 58.65 1516 .983 43.4 .815 116.75 3716 .943 66.8 1 2107 1 128.4

In this example I'll use an XSLT stylesheet - we'll see how to create one in Chapter 11 - to transform

so that it uses formatting objects. I then use the FOP processor to convert the new document into a PDF file. We'll also look at how a formatted document looks in Adobe Acrobat. XSLT style sheet

Listing 1.8 shows the style sheet

, which takes data from and formats it into a PDF file, . In this case, I use a large font for the text - 36 points. Listing 1.8. XML-XSL-FO transformation xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" version= "1.0">
margin-top="0mm" margin-bottom="10mm" margin-left="0mm" margin-right="0mm"/>
font-weight="bold"
font-size="36pt" line-height="48pt"
font-size="36pt" line-height="48pt"
font-size="36pt" line-height="48pt"
font-size="36pt" line-height="48pt"
font-size="36pt" line-height="48pt" Convert a document to a view with formatting objects

In order to convert

In a document that uses formatting objects, which I named , all you need to do is apply a style sheet. This can be done using the XSLT techniques already discussed in this chapter.

For example, to create

using Xalan, on Windows you first need to install: C:\>set classpath=c:\xalan\xalan-1_2_0_0\bin\xalan.jar; c:\xalan\xalan-j_2_0_0\bin\xerces.jar

Then apply

to generate: C:\planets>java org.apache.xalan.xslt.Process -IN planets.xml -XSL planetsPDF.xsl -OUT planets.fo

To specify document formatting

uses XSL formatting objects. This is what the file looks like (Listing 1.9): Listing 1.9. planets.fo margin-right="20mm" margin-left="20mm" margin-bottom="10mm" margin-top="10mm" page-width="300mm" page-height="400mm" margin-right=" 0mm" margin-left="0mm" margin-bottom="10mm" margin-top="0mm"/> font-family="sans-serif" line-height="48pt" font-size="36pt" font- weight="bold"> font-family="sans-serif" line-height="48pt" font-family="sans-serif" line-height="48pt" font-family="sans-serif" line-height ="48pt" font-family="sans-serif" line-height="48pt" font-family="sans-serif" line-height="48pt" Distance (million miles): 43.4 font-family="sans- serif" line-height="48pt" font-size="36pt" font-weight="bold"> font-family="sans-serif" line-height="48pt" font-family="sans-serif" line -height="48pt" font-family="sans-serif" line-height="48pt" font-family="sans-serif" line-height="48pt" font-family="sans-serif" line-height ="48pt" Distance (million miles): 66.8 font-family="sans-serif" line-height="48pt" font-size="36pt" font-weight="bold"> font-family="sans-serif " line-height="48pt" font-family="sans-serif" line-height="48pt" font-family="sans-serif" line-height="48pt" font-family="sans-serif" line -height="48pt" font-family="sans-serif" line-height="48pt" Distance (million miles): 128.4

So we have successfully created

. How can we now use it to create a formatted PDF file? Create a formatted document

To process

to create a formatted document, I'll use James Tauber's FOP processor, which he donated to the Apache XML Project.

Processor home page - http://xml.apache.org/fop; FOP can currently be downloaded from http://xml.apache.org/fop/download.html. The FOP package, including documentation, comes in zip format, so you need to extract it first. FOP is implemented as a Java JAR file,

, here I will use FOP version 0.15.

FOP can be started from the command line using the Java class, at the time of writing called

org.apache.fop.apps.CommandLine. Need to provide an XML parser - I'll use the Xerces Java parser in the file (it comes with Xalan). Let's look at how on Windows, using Java, using FOP to convert to : in this case, I specify the variable with the key to include the file, as well as the two necessary JAR files included in the downloadable package FOP - and . (This example assumes that all , and files are located in the directory; if not, provide their full paths.) C:\planets>java -cf fop.jar:xerces.jar:w3c.jar org.apache. fop apps.CommandLine planets.fo planets.pdf

The resulting file

, can be viewed in a file reader PDF Adobe Acrobat Reader, as shown in Fig. 1.8. ( Acrobat PDF Reader can be downloaded for free from www.adobe.com/products/acrobat/readermain.html.) The document shown in the figure is formatted according to a style sheet.

Rice. 1.8. PDF document created using formatting objects


PDF format - good format to display formatting objects, although it has a number of limitations - for example, it is not able to handle dynamic tables that can be expanded or collapsed on a mouse click, or clickable multicast links (both of which are included in the specification of formatting objects). Although XSL-FO is poorly supported in major browsers, this is expected to change in the future and browsers will support XSL-FO.

Didn't pass three years ever since I had the idea that it was time to learn XSLT -))). The idea arose, but everywhere there was still PHP 4 and the atrocities of Salbotron, which, to put it mildly, was no different high performance. And it was rare that any browser could boast of supporting this very XSLT. For these reasons, I postponed the study of such a promising direction until better times. At this point, we can safely say that these times have come, since PHP 5 has been released with XSLT support and a decent object model, and all top browsers already confidently handle transformations themselves, just submit XML. :)

  • http://w3c.org - committee for the development and promotion of standards world wide web Internet. At the moment, it is the primary source of almost all web-oriented standards and recommendations.
  • http://www.w3.org/TR/xml - specification of the extensible XML markup language, which is the basis of the modern web. At the time of writing, the fifth edition, version 1.0, is available, as well as the second edition, version 1.1.
  • http://www.w3.org/TR/xml-names - specification for the use of namespaces in XML.
  • http://www.w3.org/TR/xpath - specification for using the XPath language for searching parts of an XML document.
  • http://www.w3.org/TR/xsl/ - specification of the extended XSL style language.
  • http://www.w3.org/TR/xslt - XSLT transformation language specification.
  • http://validator.w3.org/ - HTML validator.
  • http://www.w3.org/TR/xhtml1/ - XHTML1.0 specification.

Translations into Russian:

  • http://www.rol.ru/news/it/helpdesk/xml01.htm - Extensible Markup Language XML1.0 (second edition). /Radik Usmanov/
  • http://www.rol.ru/news/it/helpdesk/xnamsps.htm - Namespaces in XML. /Radik Usmanov/
  • http://www.rol.ru/news/it/helpdesk/xpath01.htm - XML language Path(XPath). /Radik Usmanov/
  • http://www.rol.ru/news/it/helpdesk/xslt01.htm - XSL Transformation Language (XSLT). /Radik Usmanov/

To better understand what's going on, I recommend reading the specifications in the following order:

  • XML (this is the basis!)
  • namespaces (a mechanism for heterogeneous XML code in one file)
  • XPath (language for selecting elements from a structure tree)
  • XSLT (transformations)
  • XHTML (what you should strive for)
  • Those who are especially inquisitive can also pay attention to the extended style language XSL.

    2. Valid XHTML

    What is valid XHTML? First of all, it is an XML document that must conform to the XML specification. Secondly, it’s an almost ordinary HTML page that everyone is used to.

    Why is XHTML needed? Purely for compatibility and cross-browser reasons. A page in XHTML will be more likely to display correctly in popular browsers than regular HTML.

    For the average page riveter, the phrase XML document should mean the following:

  • The document contains an XML document declaration at the very beginning of the page:
  • The document contains one root element, which contains all the others.
  • All elements (tags) must have a closing part (
    , ).
  • Attributes always have a meaning, which must be specified in quotes (single or double). For example, .
  • Control characters & ,< и >should always wear a disguise. For example, &. The only exception is , within which special characters need not be masked.
  • Also, XHTML itself obliges the following conditions to be met:

  • The document must declare the namespace within which the HTML elements will be used.
  • The document must declare a DOCTYPE before the root element and specify one of the XHTML types and the corresponding DTD in it.
  • Example of a simple XHTML1.0 document:

    And so about everything in order.

    A declaration of an XML document that specifies its version and encoding.

    Declaration of the namespace and language used.

    Three versions of XHTML1.0 are designed for better backwards compatibility:

    • Strict - provides the greatest compliance with W3C recommendations on the part of browsers. However, the HTML code itself must follow these guidelines.
    • Transitional is a less strict match that causes the browser to behave as if it were a regular HTML document.
    • Frameset - allows you to use frames.

    XHTML1.1 is essentially the same as XHTML1.0 Strict and is intended to supplant other versions of XHTML1.0. However, compared to XHTML1.0 Strict, it has a number of differences:

  • The lang attribute has been removed, its role is played by xml:lang . (Module [ XHTMLMOD ])
  • For elements a and map instead name attribute you need to use the id attribute. (Module [ XHTMLMOD ])
  • A set of ruby ​​elements is available. (Module [RUBY])
  • So, if you want the best cross-browser compatibility and W3C compatibility, then XHTML1.1 is it!

    For these reasons, the result of my transformations will be exactly XHTML1.1.

    3. XSLT transformations

    What is XSLT? It is an XML document transformation language that was developed as part of the Extended Stylesheet Language (XSL).

    Why is XSLT needed? It allows you to implement a scheme in which the data is stored separately and its presentation is separate. That is, one XML document is transformed using another XML document (the XSL that contains the XSLT templates) into a final document. The result can be XML, HTML or a text document of any format.

    In order to use XSLT transformations, you first need to generate the correct XSL style and connect it to the XML file.

    A valid XSL document is an XML document that has the xsl namespace specified and has a stylesheet root element. In the simplest case, the style might look like this:

    This style does not contain any explicit definitions of templates or other XSL elements. However, it can already be used. To see the result, just generate an arbitrary XML document and attach this style to it:

    The line is responsible for connecting the style:

    In this case, the encoding of the result will be UTF-8, despite the fact that the source document was generated in windows-1251. Unfortunately, browsers usually don't allow you to view the code in the resulting document, but PHP5's XSLT module makes it possible to pass the resulting code into a variable that can be saved to a file. Therefore, using PHP, I will provide the source code of the resulting document:

    This code is not a valid XML document, much less XHTML1.1. In order to generate the necessary code, I will complicate the original XSL style and add there required templates and transformations. In this case, the original XML document will remain unchanged.

    As an example, I will give an XSL style that, using XSLT, will display a list of attributes of the source XML document with their values, while valid XHTML1.1 will be generated. So, the style:

    File - test.xsl
    My first XSLT My list:
  • background-color: #eee;
  • Parser developer:

    To understand how it works, I will describe each action separately:

    XML Document Declaration:

    A required attribute is to define the xsl namespace via the xmlns:xsl="http://www.w3.org/1999/XSL/Transform" attribute.

    The next step in root element stylesheet declares how the resulting document should be formed:

    Main attributes:

    • method="xml" - document output method. The resulting document will be in XML format.
    • encoding="windows-1251" - encoding of the resulting document.
    • omit-xml-declaration="no" - whether to skip the initial declaration of the XML document (). Can have the value "yes" or "no" (relevant only for html).
    • indent="yes" - form indents according to the nesting level. Can be "yes" or "no".
    • media-type="text/xml" - MIME type of the resulting document (used only for the html output method).
    • doctype-public="-//W3C//DTD XHTML 1.1//EN" - the type of the resulting document (DOCTYPE)
    • doctype-system="http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" - link to DTD

    If the output method is declared as html, then the values ​​of the encoding and media-type attributes will be inserted into the page title ( ... ) using a meta tag.

    Main template declaration:

    The xmlns="http://www.w3.org/1999/xhtml" attribute specifies the xhtml namespace that will be applied by default to this element and all child elements that do not have it explicitly specified.

    The xml:lang="ru" attribute indicates the language in which the page (future) is generated.

    This part of the style was needed to form the attributes of valid XHTML1.1 code.

    Now for XSLT transformations:

    Inserting plain text:

    The select attribute accepts an XPath expression, based on which it makes a selection. If the selection returned a list of nodes, then the loop starts running for each element.

    In this case, the selection will return a list of attributes for this (root) and all child elements.

    Checking the condition:

    In this case, if the position of the element is even (determined by the higher if), then the style of the element

  • will be registered grey colour background.

    Displaying element values:

    This code will insert into the parent element a string compiled from the name of the current element and its value. The content of the select attribute matches the XPath.

    Parser developer:

    The result of processing this style (test.xsl) will be the following code:

    Result - source code
    My first XSLT My list:
  • attr1 = Main attribute
  • attr1 = my attribute1
  • attr2 = my attribute2
  • attr5 = Free attribute
  • Parser developer: libxslt

    This code conforms to the XHTML1.1 standard and was generated from the original XML document. To check, you can use the W3C validator, which is located at http://validator.w3.org/.

    In the browser this code looks something like this:

    IE 6 FireFox 3 Opera 9.02

    Additional information on using XSLT in PHP5 can be found at http://ru2.php.net/manual/ru/book.xslt.php.

    Thinking out loud

    “Comrades, we are standing on the edge of a huge abyss! And I propose to take a big, decisive step forward!”

    2019 Anton Pribora. When copying materials from the site, please provide a link to the source.

    Let's look at a typical example of HTML rendering.

    A list of musical compositions is given in the form of an XML document.

    Richard Wagner Ride of the Valkyrie Edvard Grieg In the Cave of the Mountain King Johann Bach Toccata and Fugue in D minor Antonio Vivaldi The Seasons. Summer. Storm Giuseppe Verdi Triumphal March (Aida)

    Let's display this document as an HTML ul/li list, as shown below:

    To do this, we use the following XSLT transformation:

  • This transformation will return us the following HTML:

    • Richard Wagner - Ride of the Valkyrie
    • Edvard Grieg - In the Cave of the Mountain King
    • ...

    An XSLT transformation consists of three templates ( xsl:template). Each template serves its own essence, which gives us the ability to easily make changes and makes the code understandable.

    If we need to change the display of the list (for example, add a class attribute), then we edit the match="PlayList" template.

    If we want to change the display of list elements, then it is quite obvious that it is worth changing the match="Track" template.

    In fact, XSLT not only gives us the ability to separate data and presentation (this is the task of any template engine), but also allows us to separate representations of different entities.

    Of course, in more complex cases of separation, such separation may be difficult to achieve. It is very easy to come to a situation where a “divine template” arises that does everything, and you should also be afraid of slipping into “shot shooting” with a bunch of small templates.

    Debugging XSLT

    What I really like about XSLT is its debugging capabilities. Debugging helps to clearly see the logic of XSTL operation, the structure of the document, and the values ​​of variables.

    For example, debugging will help you see what kind of entity processes the match="/" pattern.

    In Visual Studio, XSLT debugging is launched with the keyboard shortcut ALT+F5.

    By adding the expression " . " (dot) to the Watch XPath window, we will see that the current template element is the root of the document. This is where you can place a div container, or something that pertains to the entire XML document.

    Working with XML Entities

    You will notice that in the above examples there is an entity - We can use it because we defined it at the beginning of the XSLT document

    Thus, - is output as a character with code - .

    If you need to output the string “as is”, then you should use CDATA as follows:

    xsl:text element

    I want to focus your attention on the xsl:text element. It allows you to control what exactly the TEXT element will contain. The significance of xsl:text is obvious in practice:

    XSLT template:

  • Resulting HTML:

  • Antonio Vivaldi - Seasons. Summer. Storm
  • As you can see from the example above, the absence of the xsl:text element led to the appearance of extra line breaks and spaces in the HTML.

    Of course, you can write XSLT without xsl:text , like this:

  • Such a template is difficult to read and there is a high probability that errors will appear in it during maintenance.

    You should try to ensure that the formatting of the XSLT template does not affect the result of the transformation. This is why I think using xsl:text is a good practice.

    Branching

    There are special elements for branching in XSLT: xsl:if and xsl:choose. But I think these tools are greatly overused. A more interesting technique is one that allows you to avoid cluttering the template with branches.

    Let's look at an example of implementing branches:

    Let's supplement the previous example with the ability to display the message “List is empty” if the PlayList does not contain Track elements.

    The solution using xsl:choose would be:

  • A solution using an additional template would be:

  • The second solution, in my opinion, looks nicer: the new functionality did not add new code to the old templates, new template Isolated as much as possible.

    If you need to add an image to a message about an empty list, then in the first case the xsl:when element in the match="PlayList" template will most likely swell. But in the second case, changes will only be made in a specialized template.

    In the previous example, we separated two completely different branches for rendering a list item. But what if the branches differ only slightly? Here the use of xsl:if and xsl:choose is quite justified. But I would like to show a different approach: using the mode parameter on the xsl:template element.

    In the following example, we will assign different styles to the even and odd elements of the list.

  • even odd

    Loops and sorting in XSLT

    XSLT has an xsl:for-each element for loops, but a similar effect can be achieved using regular xsl:apply-templates .

    We will display a list of songs sorted by duration.

    • Richard Wagner - Ride of the Valkyrie - 280
    • Antonio Vivaldi - Seasons. Summer. Storm - 203
    • Johann Bach - Toccata and Fugue in D minor - 187
    • Edvard Grieg - In the Cave of the Mountain King - 163
    • Giuseppe Verdi - Triumphal March (Aida) - 103

  • As you can see from the code, the first option is shorter and simpler, but it violates the principle of separation of concerns for templates. The match="PlayList" template now contains logic for displaying the Track element.

    It would seem no big deal, but imagine a problem where the list contains compositions with and without Id. For the composition with Id, you need to render the link, and for the rest, display only the text.

    Option using xsl:for-each:

    Option using xsl:apply-templates:

  • In the case of xsl:for-each, we needed to add a branch, and in the case of xsl:apply-templates, we needed to add a new template.

    If the match="PlayList" template already contained branches and logic, it would take us a while to figure out exactly where we needed to insert the branch. The xsl:apply-templates option does not have this drawback, since we are only declaring a new template, and not trying to implement old ones.

    Using xsl:for-each has another big danger. If you see a random piece of code inside a match="PlayList" pattern, you assume the current element is a PlayList, but xsl:for-each changes the context. Seeing the following code:

    You'll need to look closely at the context to understand that select="." actually selects the current Track .

    The mode="TrackName" match="Track" template was added to avoid duplication of code that displays the title. I didn't do this before because it wasn't necessary. As soon as I noticed the duplication, I refactored and moved the general display logic into a new template.

    xsl:for-each is a way to avoid creating entities. You simply add the display logic inside xsl:for-each and everything works great. The problems start later when the loop body grows, and refactoring xsl:for-each is much more difficult than removing duplicate code.

    Conclusion

    XSLT is a fairly flexible tool; it allows you to solve your problem in different ways. However, when writing XSLT, you should pay special attention to template maintainability.

    I hope my practical tips will help you write more understandable code.