The following example shows a simple but complete XML document transformed by an XSLT style sheet. The source XML document, hello.xml, contains a "Hello, World!" greeting from "An XSLT Programmer".
XML (hello.xml)
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="hello.xsl"?> <hello-world> <greeter>An XSLT Programmer</greeter> <greeting>Hello, World!</greeting> </hello-world>
The source document contains the <?xml-stylesheet …?>
processing instruction to link it to the XSLT style sheet, hello.xsl. The XSLT file contains instructions for transforming the source document into an HTML document.
XSLT (hello.xsl)
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/hello-world"> <HTML> <HEAD> <TITLE></TITLE> </HEAD> <BODY> <H1><xsl:value-of select="greeting"/></H1> <xsl:apply-templates select="greeter"/> </BODY> </HTML> </xsl:template> <xsl:template match="greeter"> <DIV>from <I><xsl:value-of select="."/></I> </DIV> </xsl:template> </xsl:stylesheet>
The effect of the transformation is to display the "Hello, World!" message on a Web page, followed by the signature of the greeter. This XSLT style sheet illustrates the basic features required of every XSLT style sheet:
<?xml version="1.0"?>
processing instruction, declaring it as an XML file.<xsl:stylesheet>
. The version
attribute specifies the version of the XSLT specification. The xmlns:xsl
attribute allows you to define a namespace alias (xsl
) for use with every XSLT element in the document (e.g., <xsl:value-of>
instead of simply <value-of>
).<xsl:template>
elements. These rules specify how various elements in the source XML document are to be transformed into result elements.The example above contains two simple template-rules. Together, they transform the contents in the source XML document into an HTML page. More complex XSLT style sheets contain either more template rules or template rules that are more complex.
Note This introductory sample is for explanatory purposes. To test the sample in Internet Explorer, you need one more file: an HTML file containing a script. This is because current versions of Internet Explorer do not ship with MSXML version 4.0 or later. For more information, and to run the Hello, World! sample, see Initiate XSLT in a Script.