一个数据库+xsl实现的完整的无级折叠的例子

String Sql="declare @t table(id int,pid int ,name varchar(20))insert @t select 1 ,0,'a'union all select 2,1,'a1'union all select 3,2,'a11'union all select 4,1,'a2'union all select 5,0,'b'SELECT  1 as Tag, NULL as Parent,id as [item!1!id],pid as [item!1!pid],    name as [item!1!name]FROM @t     FOR XML EXPLICIT";
            String XmlStr="";

            SqlConnection cn=new SqlConnection("server=127.0.0.1;uid=sa;pwd=xxx;database=test");
            cn.Open();
            SqlCommand cmd=new SqlCommand(Sql,cn);
            SqlDataReader dr = cmd.ExecuteReader();
            if(dr.Read())
            {
                XmlStr+="<root>" + dr.GetString(0) + "</root>";
            }
            XmlDocument xd=new XmlDocument();
            xd.LoadXml(XmlStr);
            dr.Close();
            cn.Close();
            Xml1.Document=xd;
            xd=null;



页面上使用一个 Xml控件,ID为Xml1.
指定TransformSource属性为下面这个xsl文件路径:
test.xsl
<?xml version="1.0" encoding="utf-8"?> 
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:template match="/"> 
<html> 
<xsl:apply-templates select="//root/item[@pid=0]"/> 
</html> 
</xsl:template> 
<xsl:template match="//item"> 
<xsl:param name="id" select="@id"/> 
<div id="{$id}"  οnclick="s{$id}.style.display=='none'?s{$id}.style.display='block':s{$id}.style.display='none'">
<xsl:choose>
<xsl:when test="count(//root/item[@pid=$id]) &gt; 0">
<span style="cursor:hand" οnclick="this.innerHTML=='+'?this.innerHTML='-':this.innerHTML='+';">+</span>
</xsl:when>
<xsl:otherwise>-</xsl:otherwise>
</xsl:choose>

<xsl:value-of select="@name"/></div> 
<div id="s{$id}" style="display:none;margin-left:30px;"> 
<xsl:apply-templates select="//root/item[@pid=$id]"/> 
</div> 
</xsl:template> 
</xsl:transform>

思路:
根具
1 id pid name这样的无级分类表结构
2 利用 for xml子句生成xml文档.
3 编写通用针对这样表结构的XSL文件,对xml文档进行样式转换. 当字段名,表名不同时,只需更改sql语句中字段名.
当表结构定义略有不同时,比如 
id为 0001 子id 为 00010001 ,00010002 即这种带路径的设计,或
id 为 1, path为 1 子id 为 3, path 为 1,3 再下级为 4, path 为 1,3,4 这种带路径的设计,只需稍改sql查询或xsl查询.

当然,在第二步,可以不用for xml子句生成xml文档,自己也可以在应用程序前台利用记录集循环得生成xml文档.


原表定义如下:
declare @t table(id int,pid int ,name varchar(20))
insert @t select 1 ,0,'a'
union all select 2,1,'a1'
union all select 3,2,'a11'
union all select 4,1,'a2'
union all select 5,0,'b'

SELECT   1 as Tag,
     NULL as Parent,
     id as [item!1!id],
     pid as [item!1!pid],
     name as [item!1!name]
    FROM @t     
    FOR XML EXPLICIT

例子利用了xml控件来执行样式转换,实际上你也可以利用XslTransform类来执行此操作.
2006.11
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值