Parse XML to Treeview List

17,705

The existing code displays the entire XML of a "leaf" XML node but just the element name of a non-leaf node. If you don't want that, you need to modify AddNode to display the content you want:

    static string GetAttributeText(XmlNode inXmlNode, string name)
    {
        XmlAttribute attr = (inXmlNode.Attributes == null ? null : inXmlNode.Attributes[name]);
        return attr == null ? null : attr.Value;
    }

    private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
    {
        // Loop through the XML nodes until the leaf is reached.
        // Add the nodes to the TreeView during the looping process.
        if (inXmlNode.HasChildNodes)
        {
            XmlNodeList nodeList = inXmlNode.ChildNodes;
            for (int i = 0; i <= nodeList.Count - 1; i++)
            {
                XmlNode xNode = inXmlNode.ChildNodes[i];
                string text = GetAttributeText(xNode, "name");
                if (string.IsNullOrEmpty(text))
                    text = xNode.Name;
                inTreeNode.Nodes.Add(new TreeNode(text));
                TreeNode tNode = inTreeNode.Nodes[i];
                AddNode(xNode, tNode);
            }
        }
        else
        {
        // If the node has an attribute "name", use that.  Otherwise display the entire text of the node.
            string text = GetAttributeText(inXmlNode, "name");
            if (string.IsNullOrEmpty(text))
                text = (inXmlNode.OuterXml).Trim();
            if (inTreeNode.Text != text)
                inTreeNode.Text = text;
                inTreeNode.Nodes.Clear();
        }
    }

And the result looks like

enter image description here (The first "namespace" node in your XML has an empty name, which is why the full text is still showing.)

Update

Now that you have shown the UI you want to achieve, what you need to do is to:

  1. Skip the root XML node and loop over its children, adding top level tree nodes for each.
  2. Skip a top-level "namespace" node if it has no name and children.

Thus:

    private void LoadTreeFromXmlDocument(XmlDocument dom)
    {
        try
        {
            // SECTION 2. Initialize the TreeView control.
            treeView1.Nodes.Clear();

            // SECTION 3. Populate the TreeView with the DOM nodes.
            foreach (XmlNode node in dom.DocumentElement.ChildNodes)
            {
                if (node.Name == "namespace" && node.ChildNodes.Count == 0 && string.IsNullOrEmpty(GetAttributeText(node, "name")))
                    continue;
                AddNode(treeView1.Nodes, node);
            }

            treeView1.ExpandAll();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    static string GetAttributeText(XmlNode inXmlNode, string name)
    {
        XmlAttribute attr = (inXmlNode.Attributes == null ? null : inXmlNode.Attributes[name]);
        return attr == null ? null : attr.Value;
    }

    private void AddNode(TreeNodeCollection nodes, XmlNode inXmlNode)
    {
        if (inXmlNode.HasChildNodes)
        {
            string text = GetAttributeText(inXmlNode, "name");
            if (string.IsNullOrEmpty(text))
                text = inXmlNode.Name;
            TreeNode newNode = nodes.Add(text);
            XmlNodeList nodeList = inXmlNode.ChildNodes;
            for (int i = 0; i <= nodeList.Count - 1; i++)
            {
                XmlNode xNode = inXmlNode.ChildNodes[i];
                AddNode(newNode.Nodes, xNode);
            }
        }
        else
        {
            // If the node has an attribute "name", use that.  Otherwise display the entire text of the node.
            string text = GetAttributeText(inXmlNode, "name");
            if (string.IsNullOrEmpty(text))
                text = (inXmlNode.OuterXml).Trim();
            TreeNode newNode = nodes.Add(text);
        }
    }

which gives

enter image description here

Share:
17,705
Kurisuchin
Author by

Kurisuchin

Updated on June 04, 2022

Comments

  • Kurisuchin
    Kurisuchin almost 2 years

    Before you ask, yes I've researched about answers regarding my question about XML but I feel like even though I found some useful ones or very close to my case, I have yet to find that spot-on answer.

    BTW, I'm using Microsoft visual Studio 2005 (C#). [Windows Application Forms]

    My problem: to parse XML (Filename.vsysvar) and show the list by GUI. Specific problem: I'm not too familiar with the .vsysvar file extension, will these work with XML? Personal problem: XML is foreign to me, I'm still trying to learn it.

    So I've tried saving the .vsysvar file as an .xml file and I found this code for XML TreeView listing:

     private void Form1_Load(object sender, EventArgs e)
        {
            // Initialize the controls and the form.
            label1.Text = "File Path";
            label1.SetBounds(8, 8, 50, 20);
            textBox1.Text = Application.StartupPath + "\\Continental.xml";
            textBox1.SetBounds(64, 8, 256, 20);
            button1.Text = "Populate the TreeView with XML";
            button1.SetBounds(8, 40, 200, 20);
            this.Text = "TreeView control from XML";
            /*this.Width = 336;
            this.Height = 368;
            treeView1.SetBounds(8, 72, 312, 264);*/
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // SECTION 1. Create a DOM Document and load the XML data into it.
                XmlDocument dom = new XmlDocument();
                dom.Load(textBox1.Text);
    
                // SECTION 2. Initialize the TreeView control.
                treeView1.Nodes.Clear();
                treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
                TreeNode tNode = new TreeNode();
                tNode = treeView1.Nodes[0];
    
                // SECTION 3. Populate the TreeView with the DOM nodes.
                AddNode(dom.DocumentElement, tNode);
                treeView1.ExpandAll();
            }
            catch (XmlException xmlEx)
            {
                MessageBox.Show(xmlEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    
        private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList nodeList;
            int i;
    
            // Loop through the XML nodes until the leaf is reached.
            // Add the nodes to the TreeView during the looping process.
            if (inXmlNode.HasChildNodes)
            {
                nodeList = inXmlNode.ChildNodes;
                for (i = 0; i <= nodeList.Count - 1; i++)
                {
                    xNode = inXmlNode.ChildNodes[i];
                    inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = inTreeNode.Nodes[i];
                    AddNode(xNode, tNode);
                }
            }
            else
            {
                // Here you need to pull the data from the XmlNode based on the
                // type of node, whether attribute values are required, and so forth.
                inTreeNode.Text = (inXmlNode.OuterXml).Trim();
            }
        }
    

    I first tried it of course with the sample.xml and it worked, when I tried now my own .xml converted from .vsysvar, that's where the problem starts. I'm not sure if I'm allowed to post this, but here's the File.vsysvar. Since it's quite long and characters are limited, here's the preview of the file:

    <?xml version="1.0" encoding="utf-8"?>
    <systemvariables version="4">
      <namespace name="" comment="">
        <namespace name="_01_Test_Preparation" comment="">
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_02_Shipping_Status_Check" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_02_Shipping_Status_Check_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_01_Get_Dem_ID" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_01_Get_Dem_ID_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_04_ECU_Version_Check_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_03_Test_Run_Init" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_04_ECU_Version_Check" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_05_DEM_Reader" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_03_Test_Run_Init_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_05_DEM_Reader_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
    </namespace>
    <namespace name="_02_Communication" comment="">
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_04_VCAN_StartLoad" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_08_XCP_Restbus_RAM_Monitor" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_01_VCAN_Output_Cyclic" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_02_VCAN_Input" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_05_VCAN_Event_Frame" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_07_VCAN_Failsafe" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_03_VCAN_Startup" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_06_VCAN_Manipulate_Input" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_09_Communication_Min_Max_Voltage" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_10_Power_On_Mask" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_11_VCAN_IgnitionOff" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_12_J1699" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_13_Input_Data_For_Algo" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_01_VCAN_Output_Cyclic_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_02_VCAN_Input_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_07_VCAN_Failsafe_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_12_J1699_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_03_VCAN_Startup_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_04_VCAN_StartLoad_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_08_XCP_Restbus_RAM_Monitor_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_05_VCAN_Event_Frame_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_06_VCAN_Manipulate_Input_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_09_Communication_Min_Max_Voltage_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_10_Power_On_Mask_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_11_VCAN_IgnitionOff_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_13_Input_Data_For_Algo_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_14_VCAN_Bus_Off_Dection_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
      <variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_02_14_VCAN_Bus_Off_Dection" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
    </namespace>
    ...
    </systemvariables>
    

    What's written in the code above is also shown in the WinForm as it is. Although it follows the TreeView format listing, what's written in the listing are the codes and not what I wanted to see: the names.

    Desired structure would be like this:

    Category A
        Property_A_1
        Property_A_2
        Property_A_3
    Category B
        Property_B_1
        Property_B_2
        Property_B_3
    

    EDIT: dbc has been a great help, I've almost cleaned the TreeView listing.

    I'm getting this:

    systemvariables
        namespace
            Category A
                Property_A_1
                Property_A_2
                Property_A_3
            Category B
                Property_B_1
                Property_B_2
                Property_B_3
    

    Am I doing it wrong or am I lacking something or what? Thanks.

  • Kurisuchin
    Kurisuchin about 9 years
    I'm getting this error.. "The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)" Then I searched as to why this happens, seems like var has been introduced to later versions of C#.
  • dbc
    dbc about 9 years
    @Kurisuchin - updated. I had forgotten var was not in VS 2005.
  • Kurisuchin
    Kurisuchin about 9 years
    Yeah. oh so that's why it wasn't working even if I changed the var, I thought only changing the var to XmlNode.Attribute would make it work. But seems like I'm wrong in a lot of things. Should be XmlAttribute only. I'll try this one then I'll update you about it.
  • Kurisuchin
    Kurisuchin about 9 years
    I tried it and the entire text doesn't show anymore thanks. although along the <namespace...> syntax the name attribute doesn't show up but it shows namespace instead. Which part of the AddNode should I modify?
  • Kurisuchin
    Kurisuchin about 9 years
    And it finally worked! Thank you so much. I removed the section 2 and section 3 from the button click event and replaced it with your work on the loadFromXmlDocument event and it still worked. So long unwanted systemvariable and namespace.