Click here to Skip to main content
15,935,248 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a xml file and I want to parse it into a treeview or in hierarchical view.

What I have tried:

XmlDataDocument xmldoc = new XmlDataDocument();
XmlNode xmlnode;
FileStream fs = new FileStream("tree.xml", FileMode.Open, FileAccess.Read);
xmlnode = xmldoc.ChildNodes[1];
Updated 16-Jun-20 22:45pm
ZurdoDev 16-Jun-20 11:28am    
Most tree view controls accept xml documents as a data source. Where are you stuck?

1 solution

There is no "automagical" way I'm afraid, but you can use a DataSet like in this Winforms example:
/// <summary>
/// Populate a treeview from an XML file using a DataSet.
/// </summary>
public partial class FormTreeview : Form
    DataSet ds;
    string xmlpath = @"test.xml";

    public FormTreeview()

        ds = new DataSet();
        int index = 0;

        // Traverse the rows
        foreach (DataRow ns in ds.Tables[0].Rows)
            Debug.Print($"{ns[0]} {ns[1]} {ns[2]}");
            string id = ns[2].ToString();

            if (id == "0")
                TreeNode parentNode = treeView1.Nodes.Add(ns[1].ToString());
                PopulateChildNodes(index, parentNode, ns[0].ToString());


    private void PopulateChildNodes(int index, TreeNode parent, string id)
        if (parent.GetNodeCount(false) == 0)
            // Traverse the settings rows and add settings if they exist
            foreach (DataRow setting in ds.Tables[1].Rows)
                if (id == setting[3].ToString())
                    Debug.Print($"        {setting[0]} {setting[1]} {setting[2]} {setting[3]}");
                    parent.Nodes.Add($"{setting[0]}: {setting[2]}");

        // Traverse the rows
        for (int i = index; i < ds.Tables[0].Rows.Count; i++)
            DataRow ns = ds.Tables[0].Rows[i];

            if (id == ns[2].ToString())
                Debug.Print($"    {ns[0]} {ns[1]} {ns[2]}");
                TreeNode childNode = parent.Nodes.Add(ns[1].ToString());
                PopulateChildNodes(index, childNode, ns[0].ToString());
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900