How to filter XML within HTML using XSLT?
Create the XML document.
<?xml version="1.0" encoding="ISO8859-1"?>
<?xml-stylesheet type="text/xsl" href="video_filter.xsl"?>
<VIDEOS>
<VIDEO>
<TITLE>Suzie</TITLE>
<DURATION type="second">30</DURATION>
</VIDEO>
<VIDEO>
<TITLE>REX</TITLE>
<DURATION type="second">130</DURATION>
</VIDEO>
<VIDEO>
<TITLE>Another Day in Paradise</TITLE>
<DURATION type="second">280</DURATION>
</VIDEO>
</VIDEOS>
To make filtering / sorting easier, it's good practice not to use mixed data types within an element.
Instead of
<DURATION>30 sec</DURATION>
use
<DURATION type="second">30</DURATION>.
Create the XSL stylesheet.
<?xml version="1.0" encoding="ISO8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr>
<th>Title</th>
<th>Duration (sec)</th>
<th>Quality</th>
<th>Bitrate (kbps)</th>
<th>Link</th>
</tr>
<xsl:for-each select="VIDEOS/VIDEO">
<xsl:if test="DURATION<50">
<tr>
<td align="left"><xsl:value-of select="TITLE"/></td>
<td align="right"><xsl:value-of select="DURATION"/></td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
To filter certain elements that match some criteria, use
<xsl:if test="condition">. The condition in the example checks if the text inside
<DURATION> is less than 50. If the condition evaluates to true, the element will be inserted in the HTML.
<xsl:if> must be placed right after
<xsl:for-each> which loops through all the elements.
Related threads:
How to filter XML data outputted in HTML
Back to
XML FAQ