要对xml中的数据用xsl按一定的条件进行排序或是按条件过滤时,事实上xsl已经为我们提供了很好的支持,现在举一个对xml数据进行排序和过滤的例子:
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="messages2.xsl"?>
<messages> <message id="101">
<to>JoannaF</to>
<from>LindaB</from>
<date>04 September 2001</date>
<subject>meeting tomorrow</subject>
<body>can you tell me what room the committee meeting will be in?</body> </message>
<message id="109">
<to>JoannaF</to>
<from>JohnH</from>
<date>04 September 2000</date>
<subject>I updated the site</subject>
<body>I've posted the lastest updates to our internal web site,as you requested</body>
</message> <message id="123">
<to>JoannaF</to>
<from>LindaB</from>
<date>05 September 2001</date>
<subject>re:meeting tomorrow</subject>
<body>Thanks.by the way,do not forget to bring your notes from the conference</body>
</message>
</messages>
现在需要根据date进行升序排序:进行升序排序的xsl文件如下:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html> <body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="messages">
<xsl:for-each select="//message">
<xsl:sort select="date" order='ascending'/>
<p>
Date:<b> <xsl:value-of select="date"/> </b><br/>
To:<b> <xsl:value-of select="to"/> </b><br/>
From:<b> <xsl:value-of select="from"/> </b><br/>
</p>
<p> <xsl:value-of select="body"/> </p>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
需要按照一定筛选条件进行筛选时的xsl为:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="messages">
<xsl:for-each select="//message" >
<!-- <xsl:if test="date!='04 September 2000'">-->
<xsl:if test="@id!='109'">
<p>
Date:<b> <xsl:value-of select="date"/> </b><br/>
To:<b> <xsl:value-of select="to"/> </b><br/>
From:<b> <xsl:value-of select="from"/> </b><br/>
</p>
<p> <xsl:value-of select="body"/> </p>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>