Load XML file data in a Treeview control in Visual Basic 2005
We have an XML file that needs to be loaded in the TreeView control. This entry shows How do we do it in VB.NET 2005.
Let's create a VB.NET Project. Drag and drop a TreeViewControl and name it tvwMetabase. Also drag a Button control and name it btnLoad. Modify the path of the following code to point to any valid xml file and run the project. On clicking your Button you should see the Treeview control loaded with the XML file's data!!
Private Sub btnLoadXML_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles btnLoad.Click
Try
Dim xmlDoc As New XmlDocument()
Dim tnNode As TreeNode
xmlDoc.Load("C:\Metabase.xml") '<--- Change this path with a valid XML file
tvwMetabase.Nodes.Clear()
tvwMetabase.Nodes.Add(xmlDoc.DocumentElement.Name)
tnNode = New TreeNode
tnNode = tvwMetabase.Nodes(0)
AddNode(xmlDoc.DocumentElement, tnNode)
Catch xmlEx As XmlException
MessageBox.Show(xmlEx.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub AddNode(ByVal inXmlNode As XmlNode, ByVal inTreeNode As TreeNode)
Dim xNode As XmlNode
Dim tNode As TreeNode
Dim nodeList As XmlNodeList
Dim i As Integer
If inXmlNode.HasChildNodes Then
nodeList = inXmlNode.ChildNodes
i = 0
While i <= nodeList.Count - 1
xNode = inXmlNode.ChildNodes(i)
inTreeNode.Nodes.Add(New TreeNode(xNode.Name))
tNode = inTreeNode.Nodes(i)
AddNode(xNode, tNode)
i += 1
End While
Else
inTreeNode.Text = (inXmlNode.OuterXml).Trim
End If
End Sub
Enjoy!
-Rahul Soni
Comments
Anonymous
April 28, 2006
Hi Rahul,
This is a neat piece of code. Thank you.
Luvy GonzalezAnonymous
August 06, 2006
urgently neededAnonymous
March 01, 2007
Thx for your info... btw, can you help me giving the code also with thedata.. I means if I use <Company name="aaa"> </company> I want also the name include in the tree view. Please help me.. you can send it to slashcanadian@gmail.com thank youAnonymous
March 01, 2007
Thx for your info... btw, can you help me giving the code also with thedata.. I means if I use <Company name="aaa"> </company> I want also the name include in the tree view. Please help me.. you can send it to slashcanadian@gmail.com thank youAnonymous
August 12, 2007
Thanks! Easy and fast:-)Anonymous
October 01, 2009
thanks for this view. But i want this is reverse process. Tree view to XML file and XML file to tree view in the windows form 2008.