Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLoad a TreeView control from an XML file
KeywordsTreeView, XML
CategoriesControls
 
Select the Project menu's References command and select the Microsoft XML, v3.0 entry (or whichever entry you have on your system). Create a DOMDocument object and use its Load method to load the XML file. Then call subroutine AddChildrenToTreeView to add the document's child nodes to the TreeView.

Subroutine AddChildrenToTreeView loops through an XML node's children. For each XML child, it creates a new TreeView node making it the child of the indicated TreeView parent node. If there is no TreeView parent node, it makes the new node have no child so it is a TreeView root node.

After creating the TreeView node, subroutine AddChildrenToTreeView calls itself recursively to add the children of the child node to the tree.

 
' Load a TreeView control from an XML file.
Private Sub LoadTreeViewFromXmlFile(ByVal file_name As _
    String, ByVal trv As TreeView)
Dim xml_doc As DOMDocument

    ' Load the XML file into the DOMDocument.
    Set xml_doc = New DOMDocument
    xml_doc.Load file_name

    ' Add the root node's children to the TreeView.
    TreeView1.Nodes.Clear
    AddChildrenToTreeView trv, Nothing, _
        xml_doc.documentElement
End Sub

' Add this XML node's children to the indicated TreeView
' node.
Private Sub AddChildrenToTreeView(ByVal trv As TreeView, _
    ByVal treeview_parent As Node, ByVal xml_node As _
    IXMLDOMElement)
Dim xml_child As IXMLDOMElement
Dim new_node As Node

    ' Examine each XML child.
    For Each xml_child In xml_node.childNodes
        ' Add the child to the TreeView.
        If treeview_parent Is Nothing Then
            Set new_node = trv.Nodes.Add(, , , _
                xml_child.nodeName)
        Else
            Set new_node = trv.Nodes.Add(treeview_parent, _
                tvwChild, , xml_child.nodeName)
        End If
        new_node.EnsureVisible

        ' Add the child's children.
        AddChildrenToTreeView trv, new_node, xml_child
    Next xml_child
End Sub
 
This version of the program uses the XML nodes' names for the TreeView nodes' text. You could modify it to display an XML node's Text value, an attribute value, or some other value instead of the node's name (which cannot contain certain characters such as spaces).
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated