How to display XML elements in HTML using XSLT?
Create an XML document with one root element
<books> and as many child elements of
<book> as needed.
<books>
<book>OpenGL Programming Guide Fourth Edition</book>
<book>Curves and Surfaces for CAGD: A Practical Guide</book>
<book>An Introduction to NURBS: With Historical Perspective</book>
<book>NURBS: From Projective Geometry to Practical Use</book>
</books>
Add the following XML declaration to the top of the page.
<?xml version="1.0" ?>
Add this line after the declaration.
<?xml-stylesheet type="text/xsl" href="book01.xsl"?>
This links the XML file to the XSL stylesheet that will be the output. The
href attribute must match the filename of the stylesheet the XML file is linked to.
Create the XSL stylesheet.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="books">
<html>
<body>
<xsl:for-each select="book">
<p><xsl:value-of select="." /></p>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Open the XML file in a browser. The result should appear as follows:
OpenGL Programming Guide Fourth Edition
Curves and Surfaces for CAGD: A Practical Guide
An Introduction to NURBS: With Historical Perspective
NURBS: From Projective Geometry to Practical Use
<?xml version="1.0"?>
An XSL Stylesheet is an XML document itself, hence the XML declaration must always be included.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
This specifies the
?namespace for the stylesheet to transform the XML data.
<xsl:output method="html" />
This specifies the format the XML data is outputted in. The current format is HTML, but it can also be XML or just plain text.
<xsl:template match="books">
This makes the XSLT engine look for the element specified and start the transformation from there.
<xsl:for-each select="book">
This matches all child elements named
<book> inside
<books>.
<xsl:value-of select="." />
This takes all data from the
<book> elements and outputs them to HTML. There is only text inside
<book></book>, this is not always the case though.
Back to
XML FAQ