[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
How_To_XML_Filter_XML_In_HTML_XSLT

How to filter XML in HTML using XSLT?

Filtering means you only display those elements from XML to the output that match certain criteria. Elements that do not match the criteria, will not be displayed in the output.

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 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</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> 


Output:


Title   Duration 
Suzie         30


To filter certain elements that match some criteria, use <xsl:if test="condition">. The condition in the example checks if the text 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 elements.

Related threads:
How to filter XML data outputted in HTML

XML FAQ

last edited (April 19, 2004) by lillu, Number of views: 2451, Current Rev: 5 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. 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 Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.