Welcome!

Industrial IoT Authors: Liz McMillan, Pat Romanski, Ravi Rajamiyer, Stackify Blog, Yeshim Deniz

Related Topics: Industrial IoT

Industrial IoT: Article

Transforming XML Documents into HTML

Transforming XML Documents into HTML

The power and elegance of XSLT - the Extensible Stylesheet Language for Transformations - stems from its ability to transform XML documents into other output formats like HTML, fulfilling one of the original promises of XML: separating content from presentation.

XSLT is particularly powerful because a single stylesheet can format all the XML documents conforming to a DTD into HTML for publication on a Web site. The stylesheet can also be used to automatically generate such features as a hyperlinked table of contents, the building of which requires substantial manual work without XML.

XSLT is also elegant, because if you need to reformat all the pages in your Web site, for instance, you need to change the code in only one place, the stylesheet, so long as your source documents are in XML.

Written primarily for content authors, technical writers, Web designers, and other nonprogrammers, this tutorial aims to demonstrate some of XSLT's power and elegance in separating content from presentation and in automatically generating narrative-oriented HTML documents while showing you how to create progressively more complex template rules - rules that are at the core of XSLT.

Review: 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. A template rule is an XSL element that matches a node in the XML source document and typically applies an output format, such as HTML, to it. For example, say you have the following simple XML document:

<?xml version="1.0"?>
<document>
<body>You've probably heard the
  propaganda by now: XML blesses you
  with a way to separate content from
  presentation.</body>
</document>
You can use a template rule to find the children of the root element and to format its contents in HTML for presentation. Here's a template rule that does just that:
<xsl:template match="/">
  <html>
    <body>
     <p><xsl:apply-templates/>
     </p>
   </body>
  </html>
</xsl:template>
In this 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="document">. 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. I'll expand on this concept below.

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 <document> node in our XML file, <xsl:apply-templates> suffices to print the meager contents of the file. If, however, the <document> 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 formatted.

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. First, we need to add an XML processing instruction to the top of the stylesheet. Second, 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/ and the Unofficial MSXML XSLT FAQ
at www.netcrucible.com/xslt/msxml-faq.htm 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>
     <p><xsl:apply-templates/></p>
    </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 Internet Explorer 5.5 or later, 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. In this case it's 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"?>
<document>
<body>You've probably heard the
  propaganda by now: XML blesses you
  with a way to separate content from
  presentation.</body>
</document>
Let's expand our minimal stylesheet to do a few more things. First, we'll modify our template rule to output the body element specifically (as opposed to all the children of the root element); second, we'll add a link to a Cascading Style Sheet 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="document">
    <html>
     <head>
      <link rel=
      "stylesheet" type=
      "text/css" href=
      "doc.css"/>
     </head>
   <body>
   <p><xsl:value-of
    select="body"/></p>
   </body>
    </html>
   </xsl:template>
</xsl:stylesheet>
This stylesheet first matches the root node explicitly by name (document), 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 code in Listing 1 (all listings can be found at www.sys-con.com/xml/sourcec.cfm). In this example only a few of the CSS rules are used, but the rest of them will be put into play as we expand our rudimentary stylesheet to process a more complex XML document.

Using CSS to complement XSLT is a powerful strategy for building Web pages - a strategy that splits presentation into what I call formatting and styling. Formatting can be seen to 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. 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 stylistic changes in one file, the Cascading Style Sheet.

Building a Complex Stylesheet
This section builds on the review above to create an XSLT stylesheet that will transform any document that conforms to our DTD into an HTML document. We'll create the stylesheet from the top down, step by step, explicating most of the template rules as we go.

Consider the generic XML document in Listing 2.

The document is based on the DTD in Listing 3. (This DTD is very loosely based on a scaled-down version of the TEI Lite DTD with some XHTML and other customizations thrown in; it's been constructed to demonstrate the XSL transformations in this tutorial and, unlike TEI Lite, isn't suitable for other uses. For information about TEI Lite see www.tei-c.org/.)

The XSLT stylesheet in Listing 4 is also based on the DTD. Why bring a DTD into this discussion? The answer is that it's best to build the stylesheet based on your DTD to ensure that all elements and attributes are processed fully and according to your requirements. The DTD provides the cues by which you build your stylesheet. That is, to build a suitable stylesheet - one that processes all the elements and attributes in your XML document fully and appropriately - you should develop your stylesheet based on your DTD, not on an XML document alone. For more information about analyzing DTDs to develop stylesheets, see Chapter 21, "DTD Analysis," in The XSL Companion, by Neil Bradley (Addison-Wesley).

Let's start building the stylesheet. Since XSL stylesheets are themselves XML documents, they should generally begin with an XML processing instruction as their first line: <?xml version="1.0"?>. The next line contains an optional document type declaration for the stylesheet to specify the stylesheet's root element, xsl:stylesheet. I'm including the document type declaration in our stylesheet because I want to declare several general entities as an internal DTD subset for use in the stylesheet. (Recall that general entities let you replace an entity with its value; that is, wherever the entity pub.date appears in the stylesheet as text, it is replaced by its value as defined in the entity declaration, here February 8, 2002.)

<!DOCTYPE xsl:stylesheet [
   <!ENTITY pub.date "February 8, 2002">
   <!ENTITY mdash "--">
   <!ENTITY nbsp " ">
   ]>
The root element for an XSLT stylesheet must be either xsl:stylesheet or xsl:transform. The xsl: prefix before stylesheet and transform is the customary XSL namespace; all the XSL elements are in the www.w3.org/1999/XSL/Transform namespace, which must be referenced as the value of the xmlns:xsl attribute of the xsl:stylesheet root element, as I've done here (see the chapter titled "XSL Transformations" in O'Reilly's XML in a Nutshell for additional information about the namespace):
<xsl:stylesheet xmlns:xsl=
  "http://www.w3.org/1999/XSL/Transform"
  version="1.0">
Next, I set the output method to HTML and include a reference to the HTML version I want to use:
<xsl:output method=
  "html" doctype-public="-//W3C//DTD
  HTML 4.0 Transitional//EN"/>
Creating an HTML Container
Now, bringing a simple template-matching rule into play, we begin building the HTML skeleton for the output file:
<xsl:template match=   "document">[...HTML SKELETON   CODE...]</xsl:template>
This template rule selects the XML document's root element, <document>, and circumfuses it with HTML code, forming a skeleton that will contain the body of the XML document. In the case of this stylesheet, the skeleton is in the form of a header, a content area, and a footer.

In the header I've used an XSL element - <xsl:value-of select="docinfo/title"/> - to select the title of the XML document and to output it in the title slot of the HTML document that I'm building.

Notice, too, that between the HTML <head> tags I've also created an HTML link to a Cascading Style Sheet, which contains as much of the styling information for my HTML formatting as possible:

<link rel="stylesheet" type="text/css" href="doc.css"/>
In the next XSL command I again select the value of the <title> tag in the XML document, this time for use as a headline atop the HTML document:
<xsl:value-of select=
"docinfo/title"/>
Skip over the rest of the HTML code in the header now and bore into the content area until you find the next command prefaced by the XSL namespace:
<xsl:apply-templates select="body"/>
This template rule selects the entire content of the body element in the XML document, processes it according to the other template rules in the stylesheet, and outputs the result at the point of this command inside the HTML container that we built when we matched on the root element earlier.

Formatting the Body
To format the body of the XML document, my stylesheet includes a template rule that selects the body element: <xsl:template match="body">. This template does three things:

  • It inserts a Table of Contents headline.
  • It calls another template that dynamically builds a table of contents.
  • It processes all <div1> elements.

The <xsl:call-template name="toc"/> command calls a macro (located toward the end of the stylesheet in the Macros section) that cycles through the six levels of <div> elements, makes a reference to the <div> element's heading in the form of a hyperlink, and numbers the section headings using the 1.1 format. (You can see what the output looks like by downloading the XML source document from the XML-Journal Web site and opening it in Internet Explorer 5.5; the hyperlinks in the displayed document are brown but aren't underlined.)

The set of macros that build the table of contents originated in the W3C's XSLT stylesheet for the XML Recommendation. Reverse engineering it is a potent method of teaching yourself some of the advanced capabilities of XSLT. The W3C's stylesheet is available in the download file for Chapter 9 of Michael Kay's book, XSLT Programmer's Reference, at www.wrox.com/. In IE5.0 or greater you can view the XML source code for the W3C's XML Recommendation at www.w3.org/TR/2000/REC-xml-20001006.xml or you can download it and view it using an editor like XML Spy.

The next set of templates in our stylesheet creates headings for the <div> elements, mapping the <head> element in <div1> to the HTML heading element <h1> and so forth through <div6> and <h6>. The template-matching rules for the head elements also call another template, named "head", which inserts an ID attribute in each heading and numbers them with the command mode="number".

Processing the Child Nodes
Finally, after building the table of contents and the headings for each <div> section, the stylesheet uses the following code to process all the children of the <div1> element:

<xsl:template match="div1">
  <xsl:apply-templates/>
</xsl:template>
In this code the <xsl:apply-templates/> simply tells the XSLT processor to process all the child elements of <div1> and to output them according to the template rules for each child element listed further down in the stylesheet. Many of these child elements are processed simply by what I've called the XHTML Quick Print Module. This template rule selects any of the elements listed in the value of the match attribute, makes a copy of the element, makes a copy of all the element's attributes, and passes them through to the target output file intact. Because my DTD contains several XHTML elements for low-lying nodes, I can use this template rule instead of writing a separate one for each XHTML element.

The complete stylesheet is presented in Listing 4.

Further Reading
On the heels of this column's terse introduction to XSLT, I suggest you spend a couple hours in your neighborhood bookstore reading the following chapters in this order:

  • Chapter 6, "Transformation: Repurposing Documents," in O'Reilly's Learning XML
  • Chapter 8, "XSL Transformations," in O'Reilly's XML in a Nutshell
  • Whatever selections you deem useful from Wrox's XSLT Programmer's Reference by Michael Kay

            Finally, take some time to browse through the resources listed on the World Wide Web Consortium's XSL page at www.w3.org/Style/XSL/. The page includes links to other tutorials, a FAQ, the XSL specifications, and a variety of resources.

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 playing with the code accompanying this column: add some elements to the DTD and the XML document and then write template-matching rules to process and output them in Internet Explorer. You may have to install the newest version of the MSXML parser to get the code to display correctly; see http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/766/msdncompositedoc.xml for details.

This column has only scratched the surface of XSLT. It's a complex but powerful programming language that, once you learn how to use it, yields vast gains in productivity that spring from the original promise of XML - separating content from presentation.

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 (0)

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.


@ThingsExpo Stories
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...