Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

From XML to HTML

In going from our XML (Listing 1) to HTML (Listing 2, which we’ll see shortly), we’ll be extracting only title, last name, and ISBN, ignoring the author’s first name. This statement points out an important characteristic of XSLT—we can extract data selectively from our XML, ignoring data that doesn’t interest us. Our target HTML is devoid of color, font, or any other styling attributes. We’re leaving all the formatting to our CSS team. However, we do want our design team to be able to plug in their CSS formatting, so we provide an agreed-upon style sheet link, which in our example is called zbStyle01.css:

<link href="css/zbStyle01.css" rel="stylesheet" type="text/css" />

Listing 2 shows the full target output HTML. The information in the web page corresponds to the XML in Listing 1. Our goal is to dynamically generate this page using XSLT.

Listing 2 A web page that lists the top ZwiftBooks sellers.

<title>ZwiftBooks Favorites</title>

<link href="css/zbStyle01.css" rel="stylesheet" type="text/css" />

<h1>ZwiftBooks Best Sellers</h1>
<ul class="zbListStyle01">
 <li>Garage Band 2 (Plummer) 0-321-33019-6</li>
 <li>HTML and CSS (Holzschlag) 0-13-185586-7</li>
 <li>XML in a Nutshell (Harold) 7343473844</li>
 <li>XSLT (Tidwell) 0-596-00053-7</li>
 <li>C++ FAQs (Cline) 0-201-30983-1</li>

Figure 3 shows how the generated web page will look, with and without the application of CSS styling.

Figure 3

Figure 3 Two views of the HTML in Listing 2.

Now that we know our starting point (the XML in Listing 1) and our end point (the HTML in Listing 2), let’s analyze the XSLT that will get us from start to end (see Listing 3).

Listing 3 The XSLT for generating the HTML from XML.

 1. <?xml version="1.0" ?>
 2. <xsl:stylesheet version="2.0"
 3.  xmlns:xsl ="http://www.w3.org/1999/XSL/Transform">
 5. <xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
 7.   <xsl:template match="/">
 8.     <html>
 9.         <head>
10.          <title>ZwiftBooks Favorites</title>
11.          <link href="css/zbStyle01.css" rel="stylesheet" type="text/css"/>
12.          </head>
13.          <body>
14.          <h1>ZwiftBooks Best Sellers</h1>
15.             <ul class="zbListStyle01">
17.             <xsl:for-each select="/books/book/title">
18.              <li>
19.              <xsl:value-of select="."/> (<xsl:value-of select="../author/lname"/>)
20.                           <xsl:value-of select="../@isbn"/>
21.              </li>
22.             </xsl:for-each>
24.             </ul>
25.         </body>
26.     </html>
27.  </xsl:template>
29. </xsl:stylesheet>
  • + Share This
  • 🔖 Save To Your Account