Chapter 2

Writing Your First XSLT Stylesheet

In This Chapter

bullet Preparing your XSLT working environment

bullet Creating a simple XML document

bullet Writing an XSLT stylesheet

bullet Running an XSLT processor

bullet Creating a result tree

G rasping XSLT is kind of like putting together a jigsaw puzzle. Even my 7-year-old knows that the best way to approach a puzzle is to first connect all the pieces of the outer border and then work your way inside, eventually filling in all the missing spaces.

In a sense, this book follows that same pattern. Chapter 1 defines the “conceptual” edges of the XSLT puzzle by talking about the cast of characters, the X-team. This chapter fills in the remaining edge pieces as it deals with the “mechanics” of XSLT — the materials you need and the process you follow for doing transformations. After you finish this chapter, the puzzle edge will all be connected; the rest of the book then focuses on filling in all that’s left of this jigsaw puzzle.

Preparing Your XSLT Working Environment

Every craftsman needs tools to perform his or her job adequately, and as a new XSL transformer, you are no exception. You need two primary software programs to add to your tool belt — a text editor and an XSLT processor.

Tip

Some software tools actually combine the capabilities of the text editor and XSLT processor within a single application. X-Factor, a tool I describe in the next section, is such an example.

Text editor

XML and XSLT documents are ordinary text files, so finding software that allows you to create and edit them is a breeze. You simply need a text editor. If you are Windows user, you can use Notepad. Or if you already have a favorite editor, then feel free to use it.

However, to help make the task of learning XSLT easier, I recommend you start by using X-Factor as your editor. X-Factor is an easy-to-use software program specifically designed to be a learning tool for XSLT. The application enables you to open up your XML source and XSLT stylesheet at the same time, perform transformations with the click of a button, and view the results of the transformation inside the application window (see Figure 2-1).

X-Factor is available as a free download from the XSLT For Dummies Web site at www.dummies.com/extras/xsltfd or from Nombas, Inc. at www.nombas.com. To set up X-Factor, download the setup file from either of the preceding locations and run setup.exe on your computer. The X-Factor setup program guides you through the installation process.

XSLT processor

The second piece of software that you need for transformations is an XSLT processor. This essential component takes the source XML document, looks at the rules you have set up in your stylesheet, performs the transformation, and outputs the results to a new file.

An XSLT processor is quite different than a text editor, such as Notepad. It usually has no real user interface or window to work with. Instead, most are command-line tools — things you’d work with only inside a command prompt window (you know, the DOS-like window that takes you back to the 1980s). In Chapter 20, I list ten XSLT processors you can download from the Web. Although you can feel free to use any of those to transform stylesheets, if you use X-Factor, the Instant SAXON processor is included with it, so you don’t need to install or configure it.

An XSLT processor parallels the engine of an automobile. When you drive a car, you’re aware that the engine is there, but it’s usually hidden from view under the hood. You interact with the engine, but minimally. You don’t say much more than “speed up” or “slow down.” In the same way, if you work with an XSLT processor directly, you give an XSLT processor the names of your XML document and XSLT stylesheet to process and tell it where you want to put the results, and it does the rest. However, if you use X-Factor, it manages the processor for you so you never have to call the processor directly.

Figure 2-1: You can use X-Factor to edit XSLT stylesheets.

Figure 2-1: You can use X-Factor to edit XSLT stylesheets.
Tip

Many XSLT commercial-grade software tools are available that provide more functionality than X-Factor. Visit the Web sites discussed in Chapter 19 to find out more about these enhanced tools.

Creating a Simple XML Document

An XSLT stylesheet never acts alone. It’s always applied to an XML document. So your first step in beginning XSL transformations is to create a simple XML document you can use as a sample.

Start out by creating a working folder on your computer into which you can put in documents and stylesheets you create or download from the XSLT For Dummies Web site. I recommend creating a new folder called xslt on your root C: drive (c:xslt), although feel free to place it anywhere convenient.

To create an XML document, open X-Factor and choose New XML Source File from the File menu. Enter the following code in the XML editor window:

<?xml version=”1.0” encoding=”UTF-16”?>

<scores>

  <score id=”1”>

    <film>A Little Princess</film>

    <composer>Patrick Doyle</composer>

    <year>1995</year>

    <grade>100</grade>

  </score>

  <score id=”2”>

    <film>Chocolat</film>

    <composer>Rachel Portman</composer>

    <year>2001</year>

    <grade>90</grade>

  </score>

  <score id=”3”>

    <film>Vertigo</film>

    <composer>Bernard Herrmann</composer>

    <year>1956</year>

    <grade>95</grade>

  </score>

  <score id=”4”>

    <film>Field of Dreams</film>

    <composer>James Horner</composer>

    <year>1989</year>

    <grade>96</grade>

  </score>

  <score id=”5”>

    <film>Dead Again</film>

    <composer>Patrick Doyle</composer>

    <year>1991</year>

    <grade>97</grade>

  </score>

</scores>

XML files use an .xml extension, so save the file as score.xml.

Tip

You can save time typing in the XML by downloading the score.xml file from the XSLT For Dummies Web site.

In this sample XML document, the first line contains what is called a processor directive <?xml version=”1.0”?>. This is simply a statement telling an XML processor: “Hello, I am an XML file. Please process me.”

The rest of the document contains the actual XML data. XML information is hierarchical: The outermost elements contain the elements that are inside of them. Therefore, the scores element contains five score elements in what is known as a parent-child relationship. (I discuss element relationships more in Chapter 3.)

Each score element has an attribute that provides an id value and has four child elements: film, composer, year, and grade.

Knowing the End Result

XSLT transforms XML documents into something new. But before you can write an XSLT stylesheet, you need to have a pretty good idea about what you want that something to look like. So, for this first example, suppose you need to create a new version of the scores.xml document that has three changes from the original:

bullet The children of each score element are turned into attributes.

bullet The grade element is removed.

bullet The year element is renamed releasedate.

Take the first element as an example:

  <score id=”1”>

    <film>A Little Princess</film>

    <composer>Patrick Doyle</composer>

    <year>1995</year>

    <grade>100</grade>

  </score>

With these changes applied, the new element looks like this:

  <score id=”1” film=”A Little Princess” composer=”Patrick Doyle” releasedate=”1995”/>

All the preliminaries are now set. You created your source XML file. You know what the target document needs to look like. You are now ready to become a XSL transformer. Yippee!

Writing an XSLT Stylesheet

As you find out in Chapter 1, XSLT code is written inside an XSLT stylesheet. To create a new stylesheet, return to X-Factor and choose New XSLT Stylesheet from the File menu. Begin by entering:

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

Everything within an XSLT stylesheet is contained inside of an xsl:stylesheet element. Don’t worry about the meaning of the xmlns attribute for now. Just type it in. You find out more about it in Chapter 3.

An XSLT stylesheet contains template rules that define what information from the original document goes into the new one and how that information is structured there.

Tip

Take a quick look at the XSLT code in this example to get a high-level overview of what XSLT is like. But don’t get too bogged down by the particulars just yet. Heck, you have the rest of the book for that.

Your first template rule converts the score element’s children into attributes:

<xsl:template match=”score”>

  <score id=”{@id}” film=”{film}” composer=”{composer}” releasedate=”{year}”></score>  

  <xsl:apply-templates/>

</xsl:template>

This template rule tells the processor to look for each score element in the document and, when the processor encounters one, to replace the score element’s original content with this new structure. The {@id} plugs in the value of the score element’s id attribute. The {film}, {composer}, and {year} expressions fill in the value of the child element that matches the text inside the brackets.

Additional template rules are defined to remove original child elements from appearing in the result document:

<xsl:template match=”grade”/>

<xsl:template match=”film”/>

<xsl:template match=”year”/>

<xsl:template match=”composer”/>

Each of these template rules says: “Hey, Mr. Processor. I’ll sit this one out. Just treat me as if I were not here.” Adding these lines is important, because the processor automatically assumes that element values want to “go with the flow” and be included in the output — unless you specifically tell it not to include them. So, if you don’t add these rules, the processor includes their content in the output document both as elements (their original form) and as attributes (the new form defined in the preceding score template rule).

The final section of the stylesheet is added to maintain scores as the parent of the score elements:

<xsl:template match=”scores”>

  <scores>

  <xsl:apply-templates/>

  </scores>

</xsl:template>

</xsl:stylesheet> 

In this template rule, the apply-templates element tells the processor to include the contents of the scores element in the output. However, apply-templates doesn’t include the tags of the element — only what’s inside the tags. Therefore, I reapply the tags to the output document by placing apply-templates in between the scores start and end tags.

An end xsl:stylesheet tag is added at the bottom of the stylesheet:

</xsl:stylesheet> 

Listing 2-1 shows the complete XSLT stylesheet.

Listing 2-1: A Complete XSLT Stylesheet

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

<!-- Template rule to convert child elements to attributes -->

<xsl:template match=”score”>

  <score id=”{@id}” film=”{film}” composer=”{composer}” releasedate=”{year}”/>  

  <xsl:apply-templates/>

</xsl:template>

<!-- Remove child elements from appearing as usual in the result document -->

<xsl:template match=”grade”/>

<xsl:template match=”film”/>

<xsl:template match=”year”/>

<xsl:template match=”composer”/>

<!-- Maintain the scores element -->

<xsl:template match=”scores”>

  <scores>

  <xsl:apply-templates/>

  </scores>

</xsl:template>

</xsl:stylesheet> 

Type this code and save it as score.xsl in the same location as your score.xml file. By convention, an XSLT stylesheet has an extension of .xsl. Alternatively, you can save time and download the score.xsl file from the XSLT For Dummies Web site.

Processing the Stylesheet

You are now officially ready to transform your first XML document. Given this momentous occasion, I feel compelled to offer a sense of ceremony:

“Ladies and gentlemen, start your processors. Let the transforming begin!”

Ok, now that the formalities are over . . .

If you’re using X-Factor, you can apply the XSLT stylesheet to the XML source document you created by clicking the Transform button. X-Factor kicks off the Instant SAXON processor behind-the-scenes to process the transformation.

Viewing the Results

After the transformation finishes in X-Factor, you have a brand spankin’ new XML document that appears in the Results view, as shown in Figure 2-2.

In its raw XML form, this new file looks like the following XML snippet:

  <scores>

  <score id=”1” film=”A Little Princess” composer=”Patrick Doyle” releasedate=”1995”/>

  <score id=”2” film=”Chocolat” composer=”Rachel Portman” releasedate=”2001”/>

  <score id=”3” film=”Vertigo” composer=”Bernard Herrmann” releasedate=”1956”/>

  <score id=”4” film=”Field of Dreams” composer=”James Horner” releasedate=”1989”/>

  <score id=”5” film=”Dead Again” composer=”Patrick Doyle” releasedate=”1991”/>

  </scores>

Figure 2-2: X-Factor’s Results View shows you the results of a transformation.

Figure 2-2: X-Factor’s Results View shows you the results of a transformation.
Tip

You see added spaces between the score elements in your file. Don’t concern yourself with them; an XML or XSLT processor ignores these spaces. However, you can get rid of extra white space when you need to, which I discuss in more detail in Chapter 13.

In X-Factor, you can save the result document by choosing Save Result Document from the File menu. Because this is the second version of score.xml, call it score2.xml.

Interestingly, you can also view the score2.xml in Internet Explorer 5.5 or higher. Using its built-in XML processor, Internet Explorer displays the resulting XML in a tree-like manner.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.150.59