Use TreeView to load XML files and treeview to load xml files
PS: as the younger brother is a beginner in programming, this article only writes the implementation method. The code is not very well written. Please forgive me!
1. Content of the xml document to be read
2. Final Implementation results
3. It seems complicated to implement, but it is quite simple to think about.
Idea: Read the XML document → get the XML root element → recursively Add sub-elements of the root element (because the tree structure is similar to XML)
Specific Code
First, register the method for loading the button
1 private void btn_LoadXml_Click (object sender, EventArgs e) 2 {3 // read the Xml file this.txt _ XmlPath. text is the file path 4 XDocument xmlfile = XDocument.Load(Path.GetFullPath(this.txt _ XmlPath. text. trim (); 5 6 // get the root element 7 XElement rootElement = xmlfile. root; 8 9 // Add the Root node 10 TreeNode node = this to the TreeView. treeView1.Nodes. add (rootElement. name. toString (); 11 12 RecursionAddNode (node. nodes, rootElement); 13}
RecursionAddNode method code this method mainly implements recursive addition to TreeView
Private void RecursionAddNode (TreeNodeCollection nodes, XElement xElement) {// obtain the nested element IEnumerable <XElement> elements = xElement. elements (); // recursively add foreach (XElement element in elements) {TreeNode node = nodes. add (element. name. toString () + ":" + GetAttributes (element); RecursionAddNode (node. nodes, element );}}
// If You Want To obtain attributes, you must add another method GetAttributes (element)
private static string GetAttributes(XElement xElement) { IEnumerable<XAttribute> attributes = xElement.Attributes(); foreach (XAttribute attribute in attributes) { return attribute.Name + "=" + attribute.Value; } return null; }
Note: I learned to read XML but read the following documents and found that many objects can be read. So I want to ask if I have read this object out of date?