How to Filter XML Data in XSLT - XSLT Tutorial

Breaking Down XSLT - Part 5

XSLT, or XSL Transformations, offers a number of ways to filter data in an XML document and produce an output stream seen by your page viewers. With XSLT, you incorporate a markup language with XPath to discover and disclose information. XML is the carrier that stores the data and XSLT is the display layer. By adding filter elements to a style sheet, you transform your XML into something that a Web browser understands and can accurately display.


XSLT elements build on each other to filter out details and show only what your reader needs to see. Sort works in partnership with and value-of to generate an output stream based on an XML element. Each element added is a command to search the XML document and locate values.

    <th>Bat Style</th>
<xsl:for-each select="catalog/bat"> - find XML element <catalog> and its child <bat>
<xsl:sort select="style"/> - sort data by style
    <td><xsl:value-of select="style"/></td> - display the data in <style>
    <td><xsl:value-of select="price"/></td> - display the data in <price>

Notice the HTML code does not display any information with for-each and sort. These lines offer instructions to the processor only. The display data begins again after <xsl:sort> with the HTML tag <tr>. Value-of tells the parser what to display.

This sample code would present an HTML table with the information under <catalog/bat>, but only show bat styles and prices. The list will be sorted based on styles.


XSL:if offers a conditional test. The parser looks at the XML document, locates the path defined by XPath and tests to see if the information is true or false then displays accordingly.

In the above example, if you wanted to display only baseball bats that cost more than $30.00, you would add an 'if' statement under for-each.

<xsl:for-each select="catalog/bat">
<xsl:if test="price < 30"> - find the <bat> with the sibling element <price> and display it if it is over $30.00


Similar to the if statement, XSL:choose allows you to test the data, but will return both the true and the false results.

<xsl:for-each select="catalog/bat">
  <td><xsl:value-of select="style"/></td>
<xsl:when test="price < 30">
  <td bgcolor="#C0C0C0">
<xsl:value-of select="style"/>
</xsl: when>
  <td><xsl:value-of select="style"/></td>

This will display all the bats, but it will then highlight ones over $30.00 with a different background color.

Filter Elements

Using the filter elements in XSLT provides control over what XML data displays and how that information looks. Every filter requires a for-each element to point out the XPath and a value-of element to display the data.