C#树形结构的保存与加载(二)
添加控件:
treeView1
button2
button3
保存代码如下:
private void xmlTreeSave(string xmlName) { //保存和读取TREE VIEW的状态 //创建一个 XmlDocument 对象 XmlDocument xmlDocument = new XmlDocument(); //创建一个 XmlElement 对象,并将其设置为根元素 XmlElement rootElement = xmlDocument.CreateElement("TreeViewState"); xmlDocument.AppendChild(rootElement); foreach (TreeNode node in treeView1.Nodes) { XmlElement element = xmlDocument.CreateElement("Node"); element.SetAttribute("Text", node.Text); element.SetAttribute("Checked", node.Checked.ToString()); foreach (TreeNode childNode in node.Nodes) { XmlElement childElement = xmlDocument.CreateElement("ChildNode"); childElement.SetAttribute("Text", childNode.Text); childElement.SetAttribute("Checked", childNode.Checked.ToString()); element.AppendChild(childElement); } rootElement.AppendChild(element); } xmlDocument.Save(xmlName); }
加载代码如下:
private void xmlTreeLoad(string xmlName) { treeView1.Nodes.Clear(); //加载 XML 文件并创建一个 XmlDocument 对象。 XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(xmlName); XmlElement rootElement = xmlDocument.DocumentElement; foreach (XmlElement element in rootElement.ChildNodes) { TreeNode node = new TreeNode(element.GetAttribute("Text")); node.Checked = Convert.ToBoolean(element.GetAttribute("Checked")); foreach (XmlElement childElement in element.ChildNodes) { TreeNode childNode = new TreeNode(childElement.GetAttribute("Text")); childNode.Checked = Convert.ToBoolean(childElement.GetAttribute("Checked")); node.Nodes.Add(childNode); } treeView1.Nodes.Add(node); } }
调用:
private void button2_Click(object sender, EventArgs e) { xmlTreeSave("TreeViewState.xml"); } private void button3_Click(object sender, EventArgs e) { xmlTreeLoad("TreeViewState.xml"); }