C#树形结构的保存与加载

窗体控件:

1、treeView1

2、button1(加载)、button2(保存)

窗体代码:

 1 private void button1_Click(object sender, EventArgs e)
 2         {
 3             treeView1.Focus();
 4             string xmlFileName = "TreeView.xml";
 5             if (System.IO.File.Exists(xmlFileName))
 6             {
 7                 WindowsForms.XmlTreeViewState TreeState = new WindowsForms.XmlTreeViewState();
 8                 TreeState.LoadTreeViewState(treeView1, xmlFileName);
 9             }
10         }
11 
12         private void Form1_Load(object sender, EventArgs e)
13         {
14             treeView1.HideSelection = false;
15         }
16 
17         private void button2_Click(object sender, EventArgs e)
18         {
19             string xmlFileName = "TreeView.xml";
20             WindowsForms.XmlTreeViewState TreeState = new WindowsForms.XmlTreeViewState();
21             TreeState.SaveTreeViewState(treeView1, xmlFileName);
22         }

 

类模块名称:XmlTreeViewState

  1 using System;
  2 using System.Xml;
  3 using System.Windows.Forms;
  4 using System.Text;
  5 
  6 //功能
  7 //本代码是在Syed Umar Anis的
  8 //http://www.codeproject.com/Articles/13099/Loading-and-Saving-a-TreeView-control-to-an-XML-fi
  9 //这个代码的基础上进行了修改并增加了能恢复TREEVIEW的展开的状态 和选中最后选择的一项
 10 
 11 //1 用XML保存和读取TREE VIEW的状态
 12 //2 将一个XML文件加载到TREEVIEW中
 13 namespace WindowsForms
 14 {
 15     public class XmlTreeViewState
 16     {
 17         public XmlTreeViewState()
 18         {
 19         }
 20 
 21         #region const...
 22         private const string XmlNodeTag = "node";
 23 
 24         /*
 25          *  <TreeView>
 26          *     <node  text = "节点1" imageindex = "0" expland = "true" lastselect = "false">
 27          *        <node  text = "节点2" imageindex = "-1" expland = "true" lastselect = "false"></node>
 28          *     </node>
 29          *  </TreeView>
 30         */
 31         private const string XmlNodeTextAtt = "text";
 32         private const string XmlNodeTagAtt = "tag";
 33         private const string XmlNodeImageIndexAtt = "imageindex";
 34         private const string XmlNodeExpandState = "expland";//展开状态
 35         private const string XmlNodeIsSelect = "lastselect";//最后选中的项
 36         private const string XmlNodeIndex = "index";//当前TreeView索引 
 37         #endregion
 38 
 39         #region 保存TREEVIEW状态
 40         public void SaveTreeViewState(TreeView treeView, string fileName)
 41         {
 42             XmlTextWriter textWriter = new XmlTextWriter(fileName, System.Text.Encoding.Unicode);
 43             textWriter.WriteStartDocument();
 44             textWriter.WriteStartElement("TreeView");
 45             SaveXmlNodes(treeView.Nodes, textWriter);
 46             textWriter.WriteEndElement();
 47             textWriter.Close();
 48         }
 49         #endregion
 50 
 51         #region 读取TreeView状态
 52         public void LoadTreeViewState(TreeView treeView, string fileName)
 53         {
 54             XmlTextReader reader = null;
 55             try
 56             {
 57                 treeView.Nodes.Clear();
 58                 // disabling re-drawing of treeview till all nodes are added
 59                 treeView.BeginUpdate();
 60                 reader = new XmlTextReader(fileName);
 61 
 62 
 63                 TreeNode parentNode = null;
 64 
 65                 while (reader.Read())
 66                 {
 67                     if (reader.NodeType == XmlNodeType.Element)
 68                     {
 69                         if (reader.Name == XmlNodeTag)
 70                         {
 71                             TreeNode newNode = new TreeNode();
 72                             bool isEmptyElement = reader.IsEmptyElement;
 73 
 74                             // loading node attributes
 75                             int attributeCount = reader.AttributeCount;
 76                             if (attributeCount > 0)
 77                             {
 78                                 for (int i = 0; i < attributeCount; i++)
 79                                 {
 80                                     reader.MoveToAttribute(i);
 81                                     SetAttributeValue(newNode, reader.Name, reader.Value);
 82                                     SetTreeViewState(treeView);
 83                                 }
 84                             }
 85 
 86                             // add new node to Parent Node or TreeView
 87                             if (parentNode != null)
 88                                 parentNode.Nodes.Add(newNode);
 89                             else
 90                                 treeView.Nodes.Add(newNode);
 91 
 92                             // making current node 'ParentNode' if its not empty
 93                             if (!isEmptyElement)
 94                             {
 95                                 parentNode = newNode;
 96                             }
 97                         }
 98                     }
 99                     // moving up to in TreeView if end tag is encountered
100                     else if (reader.NodeType == XmlNodeType.EndElement)
101                     {
102                         if (reader.Name == XmlNodeTag)
103                         {
104                             parentNode = parentNode.Parent;
105                         }
106                     }
107                     else if (reader.NodeType == XmlNodeType.XmlDeclaration)
108                     { //Ignore Xml Declaration                    
109                     }
110                     else if (reader.NodeType == XmlNodeType.None)
111                     {
112                         return;
113                     }
114                     else if (reader.NodeType == XmlNodeType.Text)
115                     {
116                         parentNode.Nodes.Add(reader.Value);
117                     }
118                 }
119             }
120             finally
121             {
122                 treeView.EndUpdate();
123                 reader.Close();
124             }
125         }
126         #endregion
127 
128         #region 设置 展开后的节点 最后选中的节点
129         private TreeNode LastSelectNode = null;//最后选中的节点
130         private TreeNode ExpandNode = null;//展开后的节点
131 
132         // Expland LastSelect
133         private void SetTreeViewState(TreeView treeView)
134         {
135             treeView.SelectedNode = ExpandNode;
136             //Expland
137             if (ExpandNode != null)
138                 ExpandNode.Expand();
139 
140             //Select
141             if (LastSelectNode != null)
142                 treeView.SelectedNode = LastSelectNode;
143         }
144         #endregion
145 
146         #region 保存XML节点
147         private void SaveXmlNodes(TreeNodeCollection nodesCollection, XmlTextWriter textWriter)
148         {
149             for (int i = 0; i < nodesCollection.Count; i++)
150             {
151                 TreeNode node = nodesCollection[i];
152                 textWriter.WriteStartElement(XmlNodeTag);// "node";
153 
154                 textWriter.WriteAttributeString(XmlNodeTextAtt, node.Text);// "text";
155                 textWriter.WriteAttributeString(XmlNodeImageIndexAtt, node.ImageIndex.ToString());//"imageindex";
156 
157                 if (node.IsExpanded == true)
158                     textWriter.WriteAttributeString(XmlNodeExpandState, node.IsExpanded.ToString());////展开状态
159 
160                 if (node.IsSelected)
161                     textWriter.WriteAttributeString(XmlNodeIsSelect, node.IsSelected.ToString());//是否选中
162 
163                 if (node.Tag != null)
164                     textWriter.WriteAttributeString(XmlNodeTagAtt, node.Tag.ToString());
165 
166                 textWriter.WriteAttributeString(XmlNodeIndex, node.Index.ToString());//Index
167 
168                 // add other node properties to serialize here
169 
170                 if (node.Nodes.Count > 0)
171                 {
172                     SaveXmlNodes(node.Nodes, textWriter);
173                 }
174                 textWriter.WriteEndElement();
175             }
176         }
177         #endregion
178 
179         #region 设置XML属性
180         private void SetAttributeValue(TreeNode node, string propertyName, string value)
181         {
182             if (propertyName == XmlNodeTextAtt) //text
183             {
184                 node.Text = value;
185             }
186             else if (propertyName == XmlNodeImageIndexAtt) //ImageIndex
187             {
188                 node.ImageIndex = int.Parse(value);
189             }
190             else if (propertyName == XmlNodeExpandState)
191             {
192                 ExpandNode = node;
193             }
194             else if (propertyName == XmlNodeIsSelect)
195             {
196                 LastSelectNode = node;
197             }
198             else if (propertyName == XmlNodeTagAtt)//tag
199             {
200                 node.Tag = value;
201             }
202             else if (propertyName == XmlNodeIndex)
203             {
204                 // 用来标识 这样看XML文件时结构清晰
205             }
206         }
207         #endregion
208 
209         #region 把XML文件读取到TREE中
210         public void LoadXmlFileInTreeView(TreeView treeView, string fileName)
211         {
212             XmlTextReader reader = null;
213             try
214             {
215                 treeView.BeginUpdate();
216                 reader = new XmlTextReader(fileName);
217 
218                 TreeNode n = new TreeNode(fileName);
219                 treeView.Nodes.Add(n);
220                 while (reader.Read())
221                 {
222                     if (reader.NodeType == XmlNodeType.Element)
223                     {
224                         bool isEmptyElement = reader.IsEmptyElement;
225                         StringBuilder text = new StringBuilder();
226                         text.Append(reader.Name);
227                         int attributeCount = reader.AttributeCount;
228                         if (attributeCount > 0)
229                         {
230                             text.Append(" ( ");
231                             for (int i = 0; i < attributeCount; i++)
232                             {
233                                 if (i != 0) text.Append(", ");
234                                 reader.MoveToAttribute(i);
235                                 text.Append(reader.Name);
236                                 text.Append(" = ");
237                                 text.Append(reader.Value);
238                             }
239                             text.Append(" ) ");
240                         }
241 
242                         if (isEmptyElement)
243                         {
244                             n.Nodes.Add(text.ToString());
245                         }
246                         else
247                         {
248                             n = n.Nodes.Add(text.ToString());
249                         }
250                     }
251                     else if (reader.NodeType == XmlNodeType.EndElement)
252                     {
253                         n = n.Parent;
254                     }
255                     else if (reader.NodeType == XmlNodeType.XmlDeclaration)
256                     {
257 
258                     }
259                     else if (reader.NodeType == XmlNodeType.None)
260                     {
261                         return;
262                     }
263                     else if (reader.NodeType == XmlNodeType.Text)
264                     {
265                         n.Nodes.Add(reader.Value);
266                     }
267 
268                 }
269             }
270             finally
271             {
272                 treeView.EndUpdate();
273                 reader.Close();
274             }
275         }
276         #endregion
277     }
278 }
XmlTreeViewState

 

posted @ 2021-07-06 17:18  Cmale  阅读(842)  评论(0编辑  收藏  举报