XSLT - xsl:template
The purpose of XSLT is to help transform an XML document into something new. To transform an XML document, XSLT must be able to do two things well:
- Find information in the XML document.
- Add additional text and/or data. In a previous example, we added HTML tags.
Both of these items are taken care of with the very important XSL element xsl:template.
XSLT - xsl:template Match Attribute
To find information in an XML document you will need to use xsl:template's match attribute. It is in this attribute that you use your knowledge of XPath to find information in your XML document.
We will be using class.xml as our example XML document.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="class.xsl"?>
If we wanted to find student elements, we would set the match attribute to a simple XPath expression: student.
Every time we find a student, let's print something out. The text we want printed must go between the opening and closing tags of <xsl:template>. Let's have it print out, "Found a learner!"
The following XSLT code will find student elements in the XML and output, "Found a learner!" for each student element. This example displays both the finding and the adding text functionality of XSLT!
XSLT Code (Work in Progress!):
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
Found a learner!
This simple XSLT does not work in Firefox because the output is not well-formed XML. However, Internet Explorer 6.0+ will view it just fine. Here is the beginning of our XSLT transformation: class1.xml.
If your browser doesn't like the class1.xml file, this is what an XSLT processor or Internet
would show you:
Found a learner! Found a learner! Found a learner! Mr. Bean
Notice that this output doesn't have a root element, which is a requirement for a well-formed XML document. Our XML document had three students and one teacher, so our XSLT printed out, "Found a learner!" three times, followed by the unmatched teacher element's text "Mr. Bean".
In a later lesson, we will show you how to filter out the unwanted text, "Mr. Bean".
We didn't create a well-formed XML document with this output, and will be showing you how to do that in the following lessons. But this lesson is important because it shows you how to find elements using the match attribute and how to add text using XSLT.
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!