PS: Because the younger brother beginner programming, this article only writes realizes the way, the code writes is not very good please forgive me!
1. XML document content that needs to be read
2. Final implementation effect
3 looks like it's complicated to realize, but it's pretty simple to think about.
Idea: Read the XML document → get the xml root element → recursively add the root element (because the tree structure is much like XML)
Specific look at the code
First to load the button registration method
1 Private voidBtn_loadxml_click (Objectsender, EventArgs e)2 {3 //read XML file this.txt_XmlPath.Text is file path4XDocument xmlfile = Xdocument.load (Path.GetFullPath ( This. Txt_XmlPath.Text.Trim ())); 5 6 //Take root element7XElement rootelement =xmlfile. Root;8 9 //Add the root node to the first TreeViewTenTreeNode node= This. TREEVIEW1.NODES.ADD (RootElement.Name.ToString ()); One A Recursionaddnode (node. Nodes, rootelement); -}
Recursionaddnode method Code This method primarily implements recursion to add to the TreeView
Private void Recursionaddnode (treenodecollection nodes, XElement XElement) { //Get nested elements IEnumerable<XElement> elements = xelement.elements (); Recursively add foreach in elements) { = nodes. ADD (element. Name.tostring () +":"+GetAttributes (Element)); Recursionaddnode (node. Nodes, Element); } }
If you want to get a property, add another method GetAttributes (Element)
Private Static string getattributes (XElement XElement) { IEnumerable<XAttribute> attributes = xelement.attributes (); foreach inch attributes) { return"=" + attribute. Value; } return NULL ; }
Note: The younger brother learns to read XML but read the following document found that many objects can be read so want to ask me to use this object read outdated?
To load an XML file using the TreeView