Thursday, September 5, 2013

How do you transform XML into XHTML using XSLT?

1. Start with an  XML document (books.xml).
2. Create an XSL stylesheet (books.xsl).
3. Keep both files at a specific location. Otherwise update the value of "href" tag with the absolute path of "books.xsl" in "books.xml".
4. Click the "books.xml" file to open in browser by default.

books.xml
--------------------------------------
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="books.xsl"?>
<catalog>
   <book id="bk9781118013847">
      <title>Beginning Perl</title>
      <author>Curtis Ovid Poe</author>
      <genre>Computer Programming</genre>
      <publisher>Wiley / Wrox</publisher>
      <price>31.99</price>
      <publish_date>August 2012</publish_date>
      <isbn>978-1-4571-2094-7</isbn>
      <description>Perl's basics and best practices for Beginners</description>
   </book>
   <book id="bk9780596527242">
      <title>Mastering Perl</title>
      <author>Brian d Foy</author>
      <genre>Computer Programming</genre>
      <publisher>O'Reilly Media</publisher>
      <price>31.99</price>
      <publish_date>July 2007</publish_date>
      <isbn>978-0-596-52724-2</isbn>
      <description>Focuses on real-life problems of debugging, maintenance, configuration</description>
   </book>
   <book id="bk9780470556801">
      <title>Perl and Apache</title>
      <author>Adam McDaniel</author>
      <genre>Computer Programming</genre>
      <publisher>Wiley / Visual</publisher>
      <price>34.99</price>
      <publish_date>January 2011</publish_date>
      <isbn>978-1-4571-3092-2</isbn>
      <description>A visual blueprint for developing dynamic Web content</description>
   </book>
</catalog>

books.xsl
--------------------------------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
  <h2>Book Details</h2>
  <table border="1" style="width:70%;">
    <tr bgcolor="#9acd32">
      <th>Id</th>
      <th>Title</th>
      <th>Author</th>     
      <th>Price ($)</th>
      <th>Publish Date</th>
      <th>Genre</th>
      <th>Description</th>
    </tr>
    <xsl:for-each select="catalog/book">
    <xsl:sort select="@id"/>
    <tr>
      <td><xsl:value-of select="@id"/></td>
      <td align="center"><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="author"/></td>     
      <td align="right"><b><xsl:value-of select="price"/></b></td>
      <td><xsl:value-of select="publish_date"/></td>
      <td><xsl:value-of select="genre"/></td>
      <td align="justify"><xsl:value-of select="description"/></td>
    </tr>
    </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

No comments :