Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to make a TreeNode by reading an Xml file. I mananged to create the ParentNodes(The Groups) but I want to add also users(the Xml child nodes) to these groups.

After running this code:

VB
Public Sub ReadGroup_Xml()
    GroupsList.Load(xml_path)

    Dim TreeNode2, TreeNode3 As TreeNode
    Dim names_list1 = GroupsList.GetElementsByTagName("Group_Name")
    Dim names_list2 = GroupsList.GetElementsByTagName("User_Initials")
    For Each item1 As XmlElement In names_list1
        'Here I add the parent nodes
        TreeNode2 = New TreeNode(item1.InnerText)
        MUsersFrm.TreeView1.Nodes.Add(TreeNode2)
        TreeNode2.ImageIndex = 0

        'Here I want to add the child nodes
        'What is the condition???
        For Each item2 As XmlElement In names_list2
            TreeNode3 = New TreeNode(item2.InnerText)
            TreeNode2.Nodes.Add(TreeNode3)
        Next
    Next
End Sub


I get the result:

Group Administrators
 - User am
Group Editors
 - User am
Group Guests
 - User am


The correct result should be:

Group Administrators
Group Editors
 - User am
Group Guests


...because only the Group Editors node contains childs nodes

I think that the commented text should have a condition before creating the child nodes.

Can you help me with this condition?
Posted

I think you could use
VB
If item1.HasChildNodes Then

to filter out the empty parent nodes.
 
Share this answer
 
It would be helpful if you posted a sample of your xml file, but here is an example based on this xml.
XML
<?xml version="1.0" encoding="utf-8" ?>
<groups>
  <group Name="Administrators"></group>
  <group Name="Editors">
    <User_Initials>abc</User_Initials>
    <User_Initials>zyz</User_Initials>
  </group>
  <group Name="Guests"></group>
</groups>


VB
Dim doc As New Xml.XmlDocument
doc.Load("xmlfile1.xml")

Dim groups As Xml.XmlNodeList = doc.SelectNodes("./groups/group")

For Each grp As Xml.XmlElement In groups
   Dim node As TreeNode = TreeView1.Nodes.Add(grp.GetAttribute("Name"))
   For Each user As Xml.XmlNode In grp.SelectNodes("./User_Initials")
      node.Nodes.Add(user.InnerText)
   Next
Next
 
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