您的位置:首页 > 其它

XSLT对XML数据进行分页且可以按某个值重新排序的方法

2007-12-06 10:57 627 查看
上一次就遇到了这样的要求,XML文件中的数据通过xslt转换成HTML,进行分页,且要根据用户的选择根据某一字段对数据进行重新排序.最初想到的是下面的方法:

<?xml version="1.0" encoding="iso-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="http://dotnet.aspx.cc/"

exclude-result-prefixes="msxsl user">

<xsl:output method="html" omit-xml-declaration="yes"/>

<xsl:template match="/">

<xsl:for-each select="//Items/Item[(position() <= $PageNo*$Count) and (

position() > (number($PageNo)-1)*$Count)]">

<xsl:sort order="ascending" data-type="text" select="title" />

</xsl:for-each>

</xsl:template>

</xsl:stylesheet>
需要重新按某一字段排序时,就使用javascript来修改xsl:sort元素中的select属性的值.但很快发现了问题:这样只是对当前页的数据重新排序,并没有真正地对XML中所有数据按要求的字段重新排序.

但真正最后,也没有一直没有想到好的解决方案来解决,只好使用所谓的"数据岛"(不知道术语是不是正确),即是先用XSLT对XML排序后生成XML,放在网页中,然后再进行分页操作.需要重新排序时,就先排序再分页,不需要重新排序时,则直接取当前面的数据就可以了.只是一直感觉这种方法非常不爽,需要用两段XSLT才能解决.

终于,后来又在一种使用XSLT的过程中想到了只使用一段XSLT解决分页时对数据重新排序的问题.代码大体如下:

<?xml version="1.0" encoding="iso-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="http://dotnet.aspx.cc/" exclude-result-prefixes="msxsl user">

<xsl:output method="html" omit-xml-declaration="yes"/>

<xsl:template match="/">

<xsl:for-each select="//Items/Item">

<xsl:if test="(position() <= $PageNo*$Count) and (position() > (number($PageNo)-1)*$Count)">

<xsl:variable name="i" select="position()"/>

<xsl:for-each select="//Items/Item">

<xsl:sort select="price" data-type="number"/>

<xsl:if test="(position() = $i)">

</xsl:if>

</xsl:for-each>

</xsl:if>

</xsl:if>

</xsl:template>

</xsl:stylesheet>

可能在效率上不是太好,具体还请大家多多指教.

PageNo指当前页码数;Count指每页记录数.下面是XML文件.

<?xml version="1.0"?>

<Items>

<Item>

<author>zk</author>

<title>yname of ttt</title>

<price>1.3</price>

</Item>

<Item>

<author>zk</author>

<title>aname of ttt</title>

<price>3.3</price>

</Item>

<Item>

<author>zk</author>

<title>xname of ttt</title>

<price>2.3</price>

</Item>

<Item>

<author>zk</author>

<title>cname of ttt</title>

<price>10.3</price>

</Item>

</Items>

[align=center]天气常如二三月,花枝不断四时春.[/align]
欢迎访问俺滴博客.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: