Populating TreeView Using XElement in C#

You can parse an XML document using XElement class available in System.Xml.Linq namespace. The following code can be used to populate a Windows Forms TreeView control using XElement .

XML Content

<?xml version="1.0" encoding="utf-8" ?>
<States>
  <State name="Tamilnadu">
    <Regions>
      <Region name="North">
        <City name="Chennai" />
        <City name="Vellore" />
      </Region>
      <Region name="South">
        <City name="Madurai"/>
        <City name="Trichy"/>
      </Region>
      <Region name="West">
        <City name="Coimbatore"/>
        <City name="Erode"/>
      </Region>
    </Regions>
  </State>
  <State name="Andhra">
    <Regions>
      <Region name="Rayalaseema">
        <City name ="Chittoor"/>
        <City name="Kurnool"/>
      </Region>
      <Region name="Telangana">
        <City name="Hydrabad" />
        <City name="Warangal" />
        <City name="Nizamabad" />
      </Region>
    </Regions>
  </State>
</States>

C# Code to Populate TreeView

private void button1_Click(object sender, EventArgs e)
        {
           var xmlData = XElement.Load(@"C:\Work\States.xml");
            TreeNode treeNode = treeView1.Nodes.Add("India");
            LoadXmlElements(xmlData, treeNode);
        }

        private void LoadXmlElements(XElement xElem, TreeNode treeNode)
        {
            foreach (XElement element in xElem.Elements())
            {
                if (element.HasElements)
                {
                    if (element.FirstAttribute != null)
                    {
                        TreeNode tempNode = treeNode.Nodes.Add(element.FirstAttribute.Value);
                        LoadXmlElements(element, tempNode);
                    }
                    else
                        LoadXmlElements(element, treeNode);                    
                }
                else
                    treeNode.Nodes.Add(element.FirstAttribute.Value);
            }
        }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: