最近在做一个产品列表的控件. 一般来说用SqlDatasource或ObjectDatasource就好了.从数据库拿分页和排序的数据是很简单的了啦.
后来想不如试试用XMLDatasource,这样不用访问数据库.结果因为对xlst和xpath不熟悉,花了不少时间才搞定.
首先说分页吧. 要用到xpath的position函数. 简单来说 xpath 就是 root/children/children[@attribute] 这样的结构.
例如要取第1~10条数据, (position 是从1开始):
XmlDataSource1.XPath ="Products/Product[position()>0 and position()<=10]";
再说排序吧. 这个就要用到xlst了,因为原来的xml数据不是排好序的.所以要用xlst文件Transform之后,再应用在XMLDatasource
xlst 排序代码如下(按价格排序):
<xsl:template match="/">
<Products>
<xsl:for-each select="Products/Product">
<xsl:sort select="@Price" data-type="number" order="ascending" />
<xsl:copy-of select="."/>
</xsl:for-each>
</Products>
</xsl:template>
<Products>
<xsl:for-each select="Products/Product">
<xsl:sort select="@Price" data-type="number" order="ascending" />
<xsl:copy-of select="."/>
</xsl:for-each>
</Products>
</xsl:template>
但是这样按价格排序的话是写死的,如果要根据客户选择的column排序的话,就要定义xsl:param 参数变量
上面的xlst就要改成这样
<xsl:sort select="@*[local-name()=$OrderBy]" data-type="{$DataType}" order="{$Direction}" />
后台C#代码动态赋值.
XmlDataSource1.TransformArgumentList.AddParam("OrderBy", "", OrderBy);