XML TreeView in VB.NET

The application shown here was my first adventure into Xml in the .Net platform. My goal was to be able to reflect any Xml file into the Windows Forms TreeView control. I found various examples online, but none I found were suited for opening all Xml files, rather they were suited to one schema or another.

The problem I ran into while writing this was more of a programming theory issue than a coding issue. This example deals with two instances of recursion, one for reading the Xml file in and one for adding the data correctly to the TreeView control.

I am aware that this application reinvents the wheel, since Internet Explorer gives the exact same functionality, but I was more interested in learning how to work with Xml files within the .Net Platform, especially using the XmlDocument class and this seemed like a good start.

The following code snippet shows the method I used to accomplish my goal. <![endif]>

Private Sub FillTree(ByVal node As XmlNode, ByVal parentnode As TreeNodeCollection).
' End recursion if the node is a text type.
If node Is Nothing Or node.NodeType = XmlNodeType.Text Or node.NodeType = XmlNodeType.CDATA Then
Return
End
 If
Dim
 tmptreenodecollection As TreeNodeCollection = AddNodeToTree(node, parentnode).
' Add all the children of the current node to the treeview.
Dim tmpchildnode As XmlNode
For Each tmpchildnode In node.ChildNodes
FillTree(tmpchildnode, tmptreenodecollection)
Next tmpchildnode
End Sub 'FillTree.
Private Function AddNodeToTree(ByVal node As XmlNode, ByVal parentnode As TreeNodeCollection)As TreeNodeCollection
Dim newchildnode As TreeNode = CreateTreeNodeFromXmlNode(node)
' if nothing to add, return the parent item.
If newchildnode Is Nothing Then
Return
 parentnode
End If ' add the newly created tree node to its parent.
If Not (parentnode Is Nothing) Then
parentnode.Add(newchildnode)
End If
Return
 newchildnode.Nodes
End Function 'AddNodeToTree.
Private Function CreateTreeNodeFromXmlNode(ByVal node As XmlNode) As TreeNode
Dim tmptreenode As New TreeNode
If node.HasChildNodes And Not (node.FirstChild.Value Is Nothing) Then
tmptreenode = New TreeNode(node.Name)
Dim tmptreenode2 As New TreeNode(node.FirstChild.Value)
tmptreenode.Nodes.Add(tmptreenode2)
Else
If
 node.NodeType <> XmlNodeType.CDATA Then
tmptreenode = New TreeNode(node.Name)
End If
End
 If
Return
 tmptreenode
End Function 'CreateTreeNodeFromXmlNode.

XMLTreeview-in-vb.net.jpg

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now