Displaying an XML File in a TreeView Control

March 21, 2009 | By

xmltree

XML’s structure is hierarchical and therefore can be displayed in a TreeView control easily. The XMLTree program displays the elements of the XML file in a TreeView control and the attributes of the selected element in a ListView control.

Wikipedia’s definition of the Extensible Markup Language or XML is a general-purpose specification for creating custom markup languages. It is classified as an extensible language, because it allows the user to define the mark-up elements. XML’s purpose is to aid information systems in sharing structured data, especially via the Internet, to encode documents, and to serialize data.

Now to the code. The load button’s click event loads the XML file selected by the user in a System.Xml.XmlDocument object and loops through the root elements. In each iteration a TreeNode object is created and populated using the three functions XmlNode2TreeNode, GetAttributes and FormatName, then added to the TreeView. The XmlNode2TreeNode function is recursive, it calls itself for each child node in the XmlNode passed to it, doing the same thing the loadButton_Click event does for the root elements.

The FormatName function returns a string formatted according to the XML standards. If the XmlNode contains text data the string returned will be <ElementName>Data</ElementName>. And if the element does not contain data the value returned will be <ElementName>. The GetAttributes function loops through the Attributes collection of the XmlNode passed to it adding them to an array of ListViewItems. The Tag property of the TreeNode object passed in the second parameter is assigned the array. This way the array can be inserted into the ListView on the right side of the form by just casting the Tag property.

For more details about XML:

 

Download Source Code

 

MaxHomework.com has the departments all over the world. The needs of the students are met despite their geographical location around the globe. Thus, homeworkgiant is a top-notch company in the sphere of homework help online websites.

Filed in: WinForms | Tags: ,

Comments (1)

  1. Hi.
    Thanks for the valuable post.
    Here has been implemented: Binding asp.net dropdownlist to an xml file.
    http://dotnetspidor.blogspot.com/2009/04/bind-aspnet-dropdownlist-to-xml-file.html