*/
Love this site? Hate it? Leave us some comments.

Other Views

corner
*/

How to Filter XML Within HTML Using XSLT

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&lt;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
corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.