Welcome!

Industrial IoT Authors: Elizabeth White, Kevin Jackson, Chris Colosimo, Pat Romanski, Liz McMillan

Related Topics: Industrial IoT

Industrial IoT: Article

An Introduction to XSLT

An Introduction to XSLT

You've probably heard the propaganda by now: XML blesses you with a way to separate content from presentation. Separation in turn yields productive gains over HTML and other data formats used to manage content.

In a process sometimes called single sourcing, the content of an XML document can be formatted for display in a Web browser, reformatted for delivery to such devices as mobile phones and handheld computers, and converted into a PDF file suitable for printing.

A news story, for example, that has been marked up in XML can be transformed into HTML for publication on a Web site, converted into Wireless Markup Language (WML) for display on a cell phone's screen, and rendered into a format from which a PDF file can be generated. Meantime, parts of the news story, such as paragraphs that supply background information about a given subject, can be reused in other XML-encoded news stories. What makes all this possible? XSLT.

Extensible Stylesheet Language for Transformations, or XSLT, is a functional programming language that enables us to bridge the gap between content and presentation by providing a means of specifying how a content-based XML document is transformed into a presentation-oriented document or data format.

This tutorial, written primarily for content authors, technical writers, Web designers, and other nonprogrammers, is the first in a short series that aims to introduce you to the basics of XSLT and help you get started using it to transform XML documents into HTML. The focus is not on data-centric documents but on such narrative-centric documents as reference manuals, help files, essays, stories, instructions, books, and magazine articles.

I'll begin by briefly summarizing the background of XSL and contrasting XSLT with XSL-FO and Cascading Style Sheets (CSS). Along the way I'll discuss what XSLT is, what it can do, and how to use it in conjunction with CSS to separate content from presentation. The next section will introduce you to XSLT's most fundamental component, the template rule, and demonstrate how to write one, culminating in a simple XSLT stylesheet that uses Internet Explorer 5.5's XSLT processor to transform a simple XML document into an HTML document.

XSLT, XSL-FO, and CSS
The birth of XSLT breaks down like this: Extensible Stylesheet Language, or XSL, was conceived as an XML application for expressing stylesheets capable of manipulating XML documents. After its submission to the W3C in 1997, XSL split into two stylesheet standards: Extensible Stylesheet Language for Transformations (XSLT) and Extensible Stylesheet Language Formatting Objects (XSL-FO).

XSLT is a language for transforming XML documents into typically other XML documents, HTML, and WML, but can also be used to produce documents in plain text and XSL-FO.

XSL-FO is used to describe the layout of XML documents for printing, with the end product usually being in Portable Document Format (PDF). XSL-FO, a complex standard that some refer to simply as XSL, may eventually also be employed to lay out Web pages, though this use is unsupported by current versions of Web browsers. You can find more information about XSLT and XSL-FO, including their specifications, on the World Wide Web Consortium's Web site, www.w3c.org. This column focuses on XSLT; later tutorials will expand on XSLT and delve into XSL-FO.

The early XSL proposals also gave rise to another breakaway standard, XPath. It grew out of the location-finding aspects of the XSL and XPointer specifications, which had been independently using similar mechanisms to find information in XML documents. XSLT uses XPath heavily to locate specific nodes or node sets within XML documents. Details about XPath can be found at www.w3c.org/TR/xpath

XSL has another related standard, though, unlike XSL, it isn't based on XML: Cascading Style Sheets. In the context of Web publishing, CSS can also be used, at least theoretically, to statically format XML documents for display, but it can't be used to transform them in any meaningful way. For example, XMetal, a tool for writing and editing in XML, uses CSS to format XML documents for display in its normal view. But until there is much stronger Web browser support for displaying XML documents with CSS, it isn't a practical option for Web publishing.

CSS isn't a competitor of XSLT. It's a method for statically formatting an XML document in a way that allows you to separate formatting and styling information from the document, but it doesn't allow you to dynamically transform an XML document into another data format. With CSS you can't manipulate the structure of an XML document, change the ordering of content, or dynamically generate a table of contents from a set of headings. Only XSLT can do that.

Using CSS to complement XSLT, however, is a powerful strategy for building Web pages - a strategy that splits presentation into what I call formatting and styling. Formatting can include basic HTML markup like headings, horizontal rules, lists, and the like. Styling, meantime, defines the visual properties of markup - its colors, sizes, widths, margins, bullet types, and so forth. Although the distinction between the two is not always clear-cut, formatting typically appears in the form of elements, styling information in the form of attribute-value pairs. For example, in <h1 style="color: olive;"> the h1 element formats the text as a first-level heading while the values of the style attribute, used for specifying inline CSS styles, reflect how the text should be styled.

You can gain a great deal of utility from separating as much styling information as possible from the formatting and placing it in a Cascading Style Sheet, although until the second major version of CSS (CSS Level 2) is better supported by browsers, your HTML formatting markup will still have to retain some styling information, such as that for tables.

Separating visual styling from formatting gives you a way to make wholesale design changes to a Web site without having to change the formatting code in every HTML document; if you've set up your Web pages properly, with all of them linking to a single CSS, you merely make the changes in one file, the Cascading Style Sheet. Cascading Style Sheets: The Definitive Guide, published by O'Reilly, provides a detailed account of how to use CSS. The W3C CSS specifications are available at www.w3c.org/Style/CSS/. In this tutorial, I'll begin demonstrating how to use CSS with XSLT to separate styling from formatting, and I'll expand on the topic in later tutorials.

Preliminaries: Principles of Separation
Other principles of separation can be immensely useful in building well-engineered, text-based Web pages with XML, XSLT, CSS, and HTML. An overarching objective is to use XML to structure content and XSLT and CSS to format it in a way that minimizes redundancy and maximizes flexibility, including the capability to repurpose content and publish it in various formats. Most of the principles that follow are best applied to narrative-oriented documents that will be published as white papers, technical manuals, help files, essays, and so forth. Keep in mind that these principles are merely a guide and that the list of exceptions is long: your data, purpose, audience, delivery format, and other factors will influence how you engineer your system's own matrix of structure, metainformation, parameters, content, and presentation.

  • XML documents: Strive to maximize the content that exists as text, not as tags, in your XML documents. In other words, content that you expect end users to see should usually be set as content, not as elements or attributes. Avoid setting content as tags, either as elements or attributes, even if doing so comes at the cost of some redundancy; it's easier for content authors to work with content that is out in the open, not hidden as the value of attributes or as elements themselves. Instead, use elements to describe the structure or content of your material; use attributes to capture metainformation about the content or its structure and to encode parameters that are used to process the content. Place recurring content, especially content that may change, such as the name of a product under development, in entities. Shy away from placing formatting or styling information in your XML documents, although it may be expedient to include some table- and image-formatting instructions.
  • XSLT stylesheets: Place as much formatting information as possible in your XSLT stylesheet and eschew using it as a container for standard content. Instead, place content out in the open in your XML documents even if doing so comes at the expense of a little duplication. However, highly variable content, such as the date of publication and the version number, may be best placed in the XSLT stylesheet as entities. It may also benefit you to make exceptions for content that varies by audience, as in the case of parameterized settings used in internationalization.
  • Cascading Style Sheets: As I mentioned above, these should complement the XSLT stylesheet by containing as many as possible of the formatting code's visual styling properties.

    In the examples that accompany this and later tutorials in the series, you'll see some of these principles at work.

XSLT's Atom: The Template Rule
In its most basic form, an XSLT stylesheet uses what are called template rules to match nodes in an XML document and transform them into another format. (Actually, it's the XSLT processor that takes an XML document, called a source tree, and an XSLT stylesheet as input and uses them to produce a result tree as output, which can then be serialized into a file, but we don't need to worry about such technicalities just yet.) A template rule is an XSL element that matches a node in the XML source document and typically applies an output format to it. For example, say you have the following simple XML document:

<?xml version="1.0"?>
<source>
<message>Greetings and
Salutations.</message>
</source>

You can use a template rule to find the children of the <source> element and to format its contents in HTML for presentation. Here's an XSLT template rule that does just that:

<xsl:template match="/">
<html>
<body>
<h1><xsl:apply- templates/></h1> </body>
</html>
</xsl:template>

In the above rule, the <xsl:template match="/"> element uses the value of its match attribute to find a node in the XML source. The forward slash operator, an XPath expression, specifies the document's root node. The rule could also match on the same node by specifying it explicitly in the template rule, that is, <xsl:template match="source">. By matching on the root node of the document, we're able to build an HTML container that provides the skeleton code (here, just <html> and <body>) for our document.

The <xsl:apply-templates> element invokes a built-in XSLT template rule that processes the children of the matched node, meaning roughly that it outputs the children. Because there's only one child of the <source> node in our XML file, <xsl:apply-templates> suffices to print the meager contents of the file. If, however, the <source> element contained more children, <xsl:apply-templates> would print all of them out too, and we'd want additional template rules to control how they're processed and outputted.

Before we can push our source XML and its accompanying stylesheet through an XSLT processor to render the HTML output, we need to do a couple more things:

  1. We need to add an XML processing instruction to the top of the stylesheet.
  2. We must wrap the template rule with the <xsl:stylesheet> element, which all XSL stylesheets require as their top-level element, and set a namespace for it (note that some versions of Internet Explorer and the MSXML parser may require a different namespace; see http://msdn.microsoft.com/" for details):
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl=
"http://www.w3.org/1999/XSL/
Transform"
version="1.0">
<xsl:template match="/">
<html>
<body>
<h1><xsl:apply- templates/ ></h1>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

We now have a minimal stylesheet that will convert our XML source to HTML. To view the output in IE 5.5 or greater, we first need to make a change to the XML source document: it must include a stylesheet processing instruction - appended after the XML processing instruction - that references our new minimal stylesheet, which in this case is located in the same directory as the source file, as the path in the href attribute's value testifies:

<?xml version="1.0"?>
<?xml:stylesheet type="text/xsl"
href="my_stylesheet.xsl"?>
<source>
<message>Greetings and Salutations.</message>
</source>

Let's expand our minimal stylesheet to do a few more things. First, we'll modify our template rule to output the message element specifically (as opposed to all the children of the root element); second, we'll add a link to a CSS that specifies the visual properties of our HTML formatting:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl= "http://www.w3.org/1999/XSL/Transform" version="1.0" >
<xsl:template match="source">
<html>
<head>
<link rel= "stylesheet"type= "text/css" href= "my_styles.css"/>
</head>
<body>
<h1><xsl:value- of select= "message"/></h1>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

This stylesheet first matches the root node explicitly by name (source), builds an HTML container for it as before, and then uses the <xsl:value-of> element to select and output the text contents of the message node. The select attribute identifies the element whose contents are to be processed.

Notice that in the stylesheet I also added a link to a CSS file in the same directory as the XSLT stylesheet. The CSS file contains the following code:

h1 { color: olive; }
This simple code selects the <h1> element and renders it in olive in Internet Explorer, effectively separating the color aspect of the heading's visual style from its HTML formatting code in the XSLT stylesheet.

Because XSLT is a programming language, there's a great deal more to it than the simple examples shown above. To reinforce this column's brief introduction, I suggest you read Chapter 6, "Transformation: Repurposing Documents," in O'Reilly's Learning XML. I also suggest you start playing around with XSLT a little on your own; it's the best way to learn how to use it. Try creating an XML document and write some simple template matching rules like those above to process your source and output it in Internet Explorer. My next column will delve deeper into XSLT to unearth its complexity and accompanying power.

More Stories By Steve Hoenisch

Steve Hoenisch is a technical writer (consultant) with Verizon
Wireless. Before becoming a technical writer and a Web developer, he
worked as a journalist and teacher. Steve has been developing Web
sites since 1996.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Robert Klawuhn 01/21/02 02:34:00 PM EST

Steve,

I am trying to make your examples work with my IE 5.5 browser. When I look at msdn.microsoft.com, I see the same namespace, so I left it alone in the files below.

I created the three files, my_xml.xml, my_stylesheet.xsl, and my_styles.css using the code from your article.

When I double-click my_xml.xml, my IE 5.5 just shows the xml. There doesn't seem to be any interaction with the xsl or css files. Is this how to launch the formatted xml?

I am very new to XML and XSL. Can you
give me any hints as to how to make this work?

Thanks,
Bob

*** my_xml.xml ***

Greetings and Salutations.

*** my_stylesheet.xsl ***

HI THERE

*** my_styles.css ***
h1 { color: olive; }

Jan Semmelink 01/21/02 03:41:00 AM EST

Your subheader reads "Using sylesheets to seperate..." instead of "Using stylesheets..." (missing "t").

@ThingsExpo Stories
In his session at @ThingsExpo, Eric Lachapelle, CEO of the Professional Evaluation and Certification Board (PECB), will provide an overview of various initiatives to certifiy the security of connected devices and future trends in ensuring public trust of IoT. Eric Lachapelle is the Chief Executive Officer of the Professional Evaluation and Certification Board (PECB), an international certification body. His role is to help companies and individuals to achieve professional, accredited and worldw...
DevOps is often described as a combination of technology and culture. Without both, DevOps isn't complete. However, applying the culture to outdated technology is a recipe for disaster; as response times grow and connections between teams are delayed by technology, the culture will die. A Nutanix Enterprise Cloud has many benefits that provide the needed base for a true DevOps paradigm.
Your homes and cars can be automated and self-serviced. Why can't your storage? From simply asking questions to analyze and troubleshoot your infrastructure, to provisioning storage with snapshots, recovery and replication, your wildest sci-fi dream has come true. In his session at @DevOpsSummit at 20th Cloud Expo, Dan Florea, Director of Product Management at Tintri, will provide a ChatOps demo where you can talk to your storage and manage it from anywhere, through Slack and similar services ...
My team embarked on building a data lake for our sales and marketing data to better understand customer journeys. This required building a hybrid data pipeline to connect our cloud CRM with the new Hadoop Data Lake. One challenge is that IT was not in a position to provide support until we proved value and marketing did not have the experience, so we embarked on the journey ourselves within the product marketing team for our line of business within Progress. In his session at @BigDataExpo, Sum...
What sort of WebRTC based applications can we expect to see over the next year and beyond? One way to predict development trends is to see what sorts of applications startups are building. In his session at @ThingsExpo, Arin Sime, founder of WebRTC.ventures, will discuss the current and likely future trends in WebRTC application development based on real requests for custom applications from real customers, as well as other public sources of information,
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that Ocean9will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Ocean9 provides cloud services for Backup, Disaster Recovery (DRaaS) and instant Innovation, and redefines enterprise infrastructure with its cloud native subscription offerings for mission critical SAP workloads.
SYS-CON Events announced today that Linux Academy, the foremost online Linux and cloud training platform and community, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Linux Academy was founded on the belief that providing high-quality, in-depth training should be available at an affordable price. Industry leaders in quality training, provided services, and student certification passes, its goal is to c...
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 20th International Cloud Expo, which will take place on June 6–8, 2017, at the Javits Center in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
SYS-CON Events announced today that Loom Systems will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Founded in 2015, Loom Systems delivers an advanced AI solution to predict and prevent problems in the digital business. Loom stands alone in the industry as an AI analysis platform requiring no prior math knowledge from operators, leveraging the existing staff to succeed in the digital era. With offices in S...
Keeping pace with advancements in software delivery processes and tooling is taxing even for the most proficient organizations. Point tools, platforms, open source and the increasing adoption of private and public cloud services requires strong engineering rigor - all in the face of developer demands to use the tools of choice. As Agile has settled in as a mainstream practice, now DevOps has emerged as the next wave to improve software delivery speed and output. To make DevOps work, organization...
SYS-CON Events announced today that T-Mobile will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on ...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and management into a ...
SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY, and the 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From ...
SYS-CON Events announced today that Infranics will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Since 2000, Infranics has developed SysMaster Suite, which is required for the stable and efficient management of ICT infrastructure. The ICT management solution developed and provided by Infranics continues to add intelligence to the ICT infrastructure through the IMC (Infra Management Cycle) based on mathemat...
Now that the world has connected “things,” we need to build these devices as truly intelligent in order to create instantaneous and precise results. This means you have to do as much of the processing at the point of entry as you can: at the edge. The killer use cases for IoT are becoming manifest through AI engines on edge devices. An autonomous car has this dual edge/cloud analytics model, producing precise, real-time results. In his session at @ThingsExpo, John Crupi, Vice President and Eng...
In the enterprise today, connected IoT devices are everywhere – both inside and outside corporate environments. The need to identify, manage, control and secure a quickly growing web of connections and outside devices is making the already challenging task of security even more important, and onerous. In his session at @ThingsExpo, Rich Boyer, CISO and Chief Architect for Security at NTT i3, will discuss new ways of thinking and the approaches needed to address the emerging challenges of securit...
The taxi industry never saw Uber coming. Startups are a threat to incumbents like never before, and a major enabler for startups is that they are instantly “cloud ready.” If innovation moves at the pace of IT, then your company is in trouble. Why? Because your data center will not keep up with frenetic pace AWS, Microsoft and Google are rolling out new capabilities In his session at 20th Cloud Expo, Don Browning, VP of Cloud Architecture at Turner, will posit that disruption is inevitable for c...
There are 66 million network cameras capturing terabytes of data. How did factories in Japan improve physical security at the facilities and improve employee productivity? Edge Computing reduces possible kilobytes of data collected per second to only a few kilobytes of data transmitted to the public cloud every day. Data is aggregated and analyzed close to sensors so only intelligent results need to be transmitted to the cloud. Non-essential data is recycled to optimize storage.