日期:2014-05-17  浏览次数:21097 次

C# winform TreeView 储存成XML文件
请问怎么把TreeView控件 储存成XML文件 包括给每个节点 添加一个Name属性

------解决方案--------------------
C# code

void CreateXml(TreeNode treeNode, XmlNode xmlNode, XmlDocument doc)
        {
            XmlNode xn;
            xn = doc.CreateElement(treeNode.Name);
            XmlAttribute att = doc.CreateAttribute("name");
            att.InnerXml = treeNode.Name;
            xn.Attributes.Append(att);
            xn.InnerText = treeNode.Name;
            xmlNode.AppendChild(xn);

            if (treeNode.Nodes.Count > 0)
            {
                foreach (TreeNode tn in treeNode.Nodes)
                {
                    CreateXml(tn, xn, doc);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = "app.xml";
            if (System.IO.File.Exists(path))
                System.IO.File.Delete(path);
            XmlDocument doc = new XmlDocument();
            XmlNode root = doc.CreateElement("root");
            doc.AppendChild(root);


            foreach (TreeNode tn in treeView1.Nodes)
            {
                CreateXml(tn, root, doc);

            }

            doc.Save(path);
        }