XML is a great way to store data with JavaScript. However, it isn’t the easiest way to see the data. All of the tags tend to hide the data rather than make it easy to understand. A generated XML file tends to lack whitespace, which makes viewing it even more difficult.
Some developers use a Cascading Style Sheet (CSS) method, but most developers prefer to use XML Stylesheet Language for Transformations (XSLT). Using XSLT has some significant advantages in flexibility and the ability to work with complex data over CSS, but XSLT is also a little harder to learn. Check here for an XSLT tutorial.
Nothing works quite so well as a quick example to demonstrate how XSLT works. To use XSLT with an XML file, you need to add a processing instruction to the XML file. The following processing instruction tells the browser displaying the Customer2.XML file to use the CustomerOut.XSLT file to format the information. This is the only difference between the Customers2.XML file and the Customers.XML file.
<?xml-stylesheet type="text/xsl" href="CustomerOut.xslt"?>
To transform an XML document into a document you can see, you build an HTML document from it. The following code provides a typical example of XSLT code that you might use for transformation purposes:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <body> <h1>Customer Listing</h1> <table border="1"> <tr> <th>Name</th> <th>Age</th> <th>Favorite Color</th> </tr> <xsl:for-each select="Customers/Customer"> <tr> <td> <xsl:value-of select="Name" /> </td> <td> <xsl:value-of select="Age" /> </td> <td> <xsl:value-of select="FavoriteColor" /> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
That’s right: XSLT is actually another form of XML, so it starts out with the XML declaration. The
The
The next steps begin creating the HTML document, complete with the tags required to do so. This is an abbreviated page. Normally, you’d include all the required tags. The page includes a heading and the start of a table.
The
Some browsers encounter problems using the example from the local drive. For example, Chrome displays a blank page when you access Customers2.XML from the local drive. To test this technique in a way that works for most browsers, copy the files to your web server and then access the XML file from the web server.