Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

XSL Transformations

XSLT is a relatively new specification, and it’s still developing in many ways. In this chapter from Inside XML, the author discusses the two parts of Extensible Styles Language (XSL) —a transformation language and a formatting language.
Like this article? We recommend

Like this article? We recommend

In this chapter, I’m going to start working with the Extensible Styles Language (XSL). XSL has two parts—a transformation language and a formatting language.

The transformation language lets you transform documents into different forms, while the formatting language actually formats and styles documents in various ways. These two parts of XSL can function quite independently, and you can think of XSL as two languages, not one. In practice, you often transform a document before formatting it because the transformation process lets you add the tags the formatting process requires. In fact, that is one of the main reasons that W3C supports XSLT as the first stage in the formatting process, as we’ll see in the next chapter.

This chapter covers the transformation language, and the next details the formatting language. The XSL transformation language is often called XSLT, and it has been a W3C recommendation since November 11, 1999. You can find the W3C recommendation for XSLT at www.w3.org/TR/xslt.

XSLT is a relatively new specification, and it’s still developing in many ways. There are some XSLT processors of the kind we’ll use in this chapter, but bear in mind that the support offered by publicly available software is not very strong as yet. A few packages support XSLT fully, and we’ll see them here. However, no browser supports XSLT fully yet.

I’ll start this chapter with an example to show how XSLT works.

Using XSLT Style Sheets in XML Documents

You use XSLT to manipulate documents, changing and working with their markup as you want. One of the most common transformations is from XML documents to HTML documents, and that’s the kind of transformation we’ll see in the examples in this chapter.

To create an XSLT transformation, you need two documents—the document to transform, and the style sheet that specifies the transformation. Both documents are well-formed XML documents.

Here’s an example; this document, planets.xml, is a well-formed XML document that holds data about three planets—Mercury, Venus, and Earth. Throughout this chapter, I’ll transform this document to HTML in various ways. For programs that can understand it, you can use the <?xml-stylesheet?> processing instruction to indicate what XSLT style sheet to use, where you set the type attribute to "text/xml" and the href attribute to the URI of the XSLT style sheet, such as planets.xsl in this example (XSLT style sheets usually have the extension .xsl).

<?xml version="1.0"?>
<?xml-stylesheet type="text/xml" href="planets.xsl"?>
<PLANETS>

    <PLANET>
        <NAME>Mercury</NAME>
        <MASS UNITS="(Earth = 1)">.0553</MASS>
        <DAY UNITS="days">58.65</DAY>
        <RADIUS UNITS="miles">1516</RADIUS>
        <DENSITY UNITS="(Earth = 1)">.983</DENSITY>
        <DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion-->
    </PLANET>

    <PLANET>
        <NAME>Venus</NAME>
        <MASS UNITS="(Earth = 1)">.815</MASS>
        <DAY UNITS="days">116.75</DAY>
        <RADIUS UNITS="miles">3716</RADIUS>
        <DENSITY UNITS="(Earth = 1)">.943</DENSITY>
        <DISTANCE UNITS="million miles">66.8</DISTANCE><!--At perihelion-->
    </PLANET>

    <PLANET>
        <NAME>Earth</NAME>
        <MASS UNITS="(Earth = 1)">1</MASS>
        <DAY UNITS="days">1</DAY>
        <RADIUS UNITS="miles">2107</RADIUS>
        <DENSITY UNITS="(Earth = 1)">1</DENSITY>
        <DISTANCE UNITS="million miles">128.4</DISTANCE><!--At perihelion-->
    </PLANET>
</PLANETS>

XSL Style Sheets

Here’s what the style sheet planets.xsl might look like. In this case, I’m converting planets.xml into HTML, stripping out the names of the planets, and surrounding those names with HTML <P> elements:

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

    <xsl:template match="PLANETS">
        <HTML>
            <xsl:apply-templates/>
        </HTML>
    </xsl:template>

    <xsl:template match="PLANET">
        <P>
            <xsl:value-of select="NAME"/>
        </P>
    </xsl:template>
</xsl:stylesheet>

All right, we have an XML document and the style sheet we’ll use to transform it. So, how exactly do you transform the document?

Making a Transformation Happen

You can transform documents in three ways:

  • In the server. A server program, such as a Java servlet, can use a style sheet to transform a document automatically and serve it to the client. One such example is the XML Enabler, which is a servlet that you’ll find at the XML for Java Web site, www.alphaworks.ibm.com/tech/xml4j.

  • In the client. A client program, such as a browser, can perform the transformation, reading in the style sheet that you specify with the <?xml-stylesheet?> processing instruction. Internet Explorer can handle transformations this way to some extent.

  • With a separate program. Several standalone programs, usually based on Java, will perform XSLT transformations. I’ll use these programs primarily in this chapter.

In this chapter, I’ll use standalone programs to perform transformations because those programs offer by far the most complete implementations of XSLT. I’ll also take a look at using XSLT in Internet Explorer.

Two popular programs will perform XSLT transformations: XT and XML for Java.

James Clark’s XT

You can get James Clark’s XT at www.jclark.com/xml/xt.html. Besides XT itself, you’ll also need a SAX-compliant XML parser, such as the one we used in the previous chapter that comes with the XML for Java packages, or James Clark’s own XP parser, which you can get at www.jclark.com/xml/

xp/ index.html.

XT is a Java application. Included in the XT download is the JAR file you’ll need, xt.jar. The XT download also comes with sax.jar, which holds James Clark’s SAX parser. You can also use the XML for Java parser with XT; to do that, you must include both xt.jar and xerces.jar in your CLASSPATH, something like this:

%set CLASSPATH=%CLASSPATH%;C:\XML4J_3_0_1\xerces.jar;C:\xt\xt.jar;

Then you can use the XT transformation class, com.jclark.xsl.sax.Driver. You supply the name of the SAX parser you want to use, such as the XML for Java class org.apache.xerces.parsers.SAXParser, by setting the com.jclark.xsl.sax.parser variable with the java -D switch. Here’s how I use XT to transform planets.xml, using planets.xsl, into planets.html:

%java -Dcom.jclark.xsl.sax.parser=
org.apache.xerces.parsers.SAXParser 
com.jclark.xsl.sax.Driver planets.xml planets.xsl planets.html

XT is also packaged as a Win32 exe. To use xt.exe, however, you will need the Microsoft Java Virtual Machine (VM) installed (included with Internet Explorer). Here’s an example in Windows that performs the same transformation as the previous command:

C:\>xt planets.xml planets.xsl planets.html

XML for Java

You can also use the IBM alphaWorks XML for Java XSLT package, called LotusXSL. LotusXSL implements an XSLT processor in Java that can be used from the command line, in an applet or a servlet, or as a module in another program. By default, it uses the XML4J XML parser, but it can interface to any XML parser that conforms to the either the DOM or the SAX specification.

Here’s what the XML for Java site says about LotusXSL: "LotusXSL 1.0.1 is a complete and a robust reference implementation of the W3C Recommendations for XSL Transformations (XSLT) and the XML Path Language (XPath)."

You can get LotusXSL at www.alphaworks.ibm.com/tech/xml4j; just click the XML item in the frame at left, click LotusXSL, and then click the Download button (or you can go directly to www.alphaworks.ibm.com/tech/lotusxsl, although that URL may change). The download includes xerces.jar, which includes the parsers that the rest of the LotusXSL package uses (although you can use other parsers), and xalan.jar, which is the LotusXSL JAR file. To use LotusXSL, make sure that you have xalan.jar in your CLASSPATH; to use the XML for Java SAX parser, make sure that you also have xerces.jar in your CLASSPATH, something like this:

%set CLASSPATH=
%CLASSPATH%;C:\lotusxsl_1_0_1\xalan.jar;C:\xsl\lotusxsl_1_0_1\xerces.jar;

Unfortunately, the LotusXSL package does not have a built-in class that will take a document name, a style sheet name, and an output file name like XT. However, I’ll create one named xslt, and you can use this class quite generally for transformations. Here’s what xslt.java looks like:

import org.apache.xalan.xslt.*;

public class xslt
{
    public static void main(String[] args)
    {
        try {
            XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
            processor.process(new XSLTInputSource(args[0]),
                new XSLTInputSource(args[1]),
                new XSLTResultTarget(args[2]));
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
        }
    }
}

After you’ve set the CLASSPATH as indicated, you can create xslt.class with javac like this:

%javac xslt.java

The file xslt.class is all you need. After you’ve set the CLASSPATH as indicated, you can use xslt.class like this to transform planets.xml, using the style sheet planets.xsl, into planets.html:

%java xslt planets.xml planets.xsl planets.html

What does planets.html look like? In this case, I’ve set up planets.xsl to simply place the names of the planets in <P> HTML elements. Here are the results, in planets.html:

<HTML>

    <P>Mercury</P>

    <P>Venus</P>

    <P>Earth</P>
</HTML>

That’s the kind of transformation we’ll see in this chapter.

There’s another way to transform XML documents without a standalone program—you can use a client program such as a browser to transform documents.

Using Browsers to Transform XML Documents

Internet Explorer includes a partial implementation of XSLT; you can read about Internet Explorer support at http://msdn.microsoft.com/xml/XSLGuide/. That support is based on the W3C XSL working draft of December 16, 1998 (which you can find at www.w3.org/TR/1998/WD-xsl-19981216.html); as you can imagine, things have changed considerably since then.

To use planets.xml with Internet Explorer, I have to make a few modifications. For example, I have to convert the type attribute in the <?xml-stylesheet?> processing instruction from "text/xml" to "text/xsl":

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="planets.xsl"?>
<PLANETS>

    <PLANET>
        <NAME>Mercury</NAME>
        <MASS UNITS="(Earth = 1)">.0553</MASS>
        <DAY UNITS="days">58.65</DAY>
        <RADIUS UNITS="miles">1516</RADIUS>
        <DENSITY UNITS="(Earth = 1)">.983</DENSITY>
        <DISTANCE UNITS="million miles">43.4</DISTANCE><!--At perihelion-->
    </PLANET>

    <PLANET>
        <NAME>Venus</NAME>
        <MASS UNITS="(Earth = 1)">.815</MASS>
        <DAY UNITS="days">116.75</DAY>
        <RADIUS UNITS="miles">3716</RADIUS>
        <DENSITY UNITS="(Earth = 1)">.943</DENSITY>
        <DISTANCE UNITS="million miles">66.8</DISTANCE><!--At perihelion-->
    </PLANET>

    <PLANET>
        <NAME>Earth</NAME>
        <MASS UNITS="(Earth = 1)">1</MASS>
        <DAY UNITS="days">1</DAY>
        <RADIUS UNITS="miles">2107</RADIUS>
        <DENSITY UNITS="(Earth = 1)">1</DENSITY>
        <DISTANCE UNITS="million miles">128.4</DISTANCE><!--At perihelion-->
    </PLANET>
</PLANETS>

I can also convert the style sheet planets.xsl for use in Internet Explorer. A major difference between the W3C XSL recommendation and the XSL implementation in Internet Explorer is that Internet Explorer doesn’t implement any default XSL rules (which I’ll discuss in this chapter). This means that I have to explicitly include an XSL rule for the root of the document, which you specify with /. I also have to use a different namespace in the style sheet, http://www.w3.org/TR/WD-xsl, and omit the version attribute in the <xsl:stylesheet> element:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">

    <xsl:template match="/">
        <HTML>
            <xsl:apply-templates/>
        </HTML>
    </xsl:template>

    <xsl:template match="PLANETS">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="PLANET">
        <P>
            <xsl:value-of select="NAME"/>
        </P>
    </xsl:template>
</xsl:stylesheet>

You can see the results of this transformation in Figure 13.1.

Figure 13.1  Performing an XSL transformation in Internet Explorer.

We now have an overview of XSL transformations and have seen them at work. It’s time to see how to create XSLT style sheets in detail.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020