XSLT - Well-Formed Output
Up to this point, we haven't been producing output that was well-formed XML. However, it isn't that much code to make your XSLT output well-formed. The trick is matching the original root element in an XSLT template and inserting a new root element for your output.
We will once again be using the class.xml document.
XML Code:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="class.xsl"?>
<class>
<student>Jack</student>
<student>Harry</student>
<student>Rebecca</student>
<teacher>Mr. Bean</teacher>
</class>
XSLT - Match the Root Element
Our previous XSLT code already had to match the original root element, so we don't have that much work to do. Here is the old XSLT code:
XSLT Code (Work in Progress!):
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="class">
<xsl:apply-templates select="student"/>
</xsl:template>
<xsl:template match="student">
Found a learner!
</xsl:template>
</xsl:stylesheet>
Original XSLT Output:
Found a learner! Found a learner! Found a learner!
As you can see, we aren't outputting any elements, let alone a well-formed XML document. Because we teach a lot of web technologies, let's make our output into a well-formed XML/XHTML file.
To do this, we are going to need to add an <html> (root element) tag, a <body> tag, and maybe some <p> tags.
XSLT - Replacing the Old Root Element
In the template that matches the original root element, we will insert the <html> tag to be the output's root element. We can also put the <body> tag there.
In the template that matches the student elements, we can insert a <p> tag to make a separate paragraph for each student.
XSLT Code (Work in Progress!):
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="class">
<html>
<body>
<xsl:apply-templates select="student"/>
</body>
</html>
</xsl:template>
<xsl:template match="student">
<p>
Found a learner!
</p>
</xsl:template>
</xsl:stylesheet>
You can view our updated XML/XSLT code here: class3.xml. You should be able to view this well-formed XML/XHTML document in most browsers. The XSLT output that our updated code produces is below:
XSLT Output:
<html>
<body>
<p>Found a learner!</p>
<p>Found a learner!</p>
<p>Found a learner!</p>
</body>
</html>
Presto! You have created some XSLT output that is well-formed XML! And, as a bonus, it is also an XHTML document that can be viewed in web browsers!
Download Tizag.com's XML Book
If you would rather download the PDF of this tutorial, check out our
XML eBook from the Tizag.com store. Found Something Wrong in this Lesson?Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time! |