数据库取值形成xml实现tree

SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=nood;User=sa;Password=123");
        SqlCommand comm = new SqlCommand("select * from tree_info", conn);
        conn.Open();
        SqlDataReader reader = comm.ExecuteReader();
        //新建XML文档
        XmlDocument doc = new XmlDocument();
        XmlElement root;
        XmlElement element;
        //插入xml声明
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, "yes");
        doc.InsertBefore(dec, doc.DocumentElement);
        //用来记录根节点元素
        ArrayList elements = new ArrayList();
        //插入第一个节点
        reader.Read();
        element = doc.CreateElement((string)reader["nodename"]);
        elements.Add(element);
        doc.InsertAfter(element,dec);
        //插入后面的子节点
        while (reader.Read())
        {
            //创建子节点
            element = doc.CreateElement((string)reader["nodename"]);
           
            elements.Add(element);
            //找到它的父节点,然后添加到父节点下
            root =(XmlElement)elements[int.Parse(reader["adderss"].ToString())-1];
            root.AppendChild(element);
        }
       
        //保存xml文件
        FileStream fs = new FileStream(@"d:\temp\names.xml", FileMode.Create);
        doc.Save(fs);
        fs.Close();
        //设置xml数据源控件并把它绑定到TreeView控件上
        XmlDataSource1.DataFile = @"d:\temp\names.xml";
        TreeView1.DataSource = XmlDataSource1;
        TreeView1.DataBind();

posted on 2011-03-11 16:03  MyBeN  阅读(157)  评论(0编辑  收藏  举报

导航