Treeview to XML in VB.net

  • Thread starter Thread starter C. A. Kelly
  • Start date Start date
C

C. A. Kelly

I have seen lots of posts for populating a treeview from a XML file but
haven't been able to find/figure out how to go from a treeview to XML.
 
Friend Module Module1
Public Sub kcXML2Tree(ByVal XMLFilepath As String, ByVal kcTreeview As
TreeView)
Dim XMLDoc As New Xml.XmlDocument
Dim XMLNode As Xml.XmlNode
Dim ParentNode As TreeNode

If kcTreeview Is Nothing Then
Throw New ArgumentNullException("TreeView")
End If

Try
XMLDoc.Load(XMLFilepath)
Catch e As Exception
Throw New Exception(e.Message)
End Try

For Each XMLNode In XMLDoc.DocumentElement.ChildNodes
ParentNode = kcTreeview.Nodes.Add(XMLNode.Attributes(0).Value)
If XMLNode.ChildNodes.Count > 0 Then
AddChildNodes(XMLNode, ParentNode)
End If
Next
End Sub

Private Sub AddChildNodes(ByVal XMLNode As Xml.XmlNode, ByVal ParentNode
As TreeNode)

Dim ChildXMLNode As Xml.XmlNode
Dim NewNode As TreeNode

For Each ChildXMLNode In XMLNode.ChildNodes
NewNode = ParentNode.Nodes.Add(ChildXMLNode.Attributes(0).Value)

If ChildXMLNode.ChildNodes.Count > 0 Then
AddChildNodes(ChildXMLNode, NewNode)
End If
Next

End Sub

Public Sub kcTree2XML(ByVal XMLFilePath As String, ByVal kcTreeview As
TreeView)
Dim XMLDoc As New Xml.XmlDocument
Dim RootNode As TreeNode
Dim NewXMLNode As Xml.XmlNode
Dim XMLAttribute As Xml.XmlAttribute

XMLDoc.LoadXml(("<?xml version='1.0' ?>" & _
"<XMLTreeView>" & _
"</XMLTreeView>"))


For Each RootNode In kcTreeview.Nodes
NewXMLNode = XMLDoc.CreateNode(Xml.XmlNodeType.Element, "Node",
"Node", "")
XMLAttribute = XMLDoc.CreateAttribute("name")
XMLAttribute.Value = RootNode.Text

NewXMLNode.Attributes.Append(XMLAttribute)
XMLDoc.DocumentElement.AppendChild(NewXMLNode)

SaveChildNodes(NewXMLNode, RootNode, XMLDoc)
Next

XMLDoc.Save(XMLFilePath)

End Sub

Private Sub SaveChildNodes(ByVal XMLNode As Xml.XmlNode, ByVal
ParentNode As TreeNode, ByVal XMLDoc As Xml.XmlDocument)
Dim ChildNode As TreeNode
Dim NewXMLNode As Xml.XmlNode
Dim XMLAttribute As Xml.XmlAttribute

For Each ChildNode In ParentNode.Nodes
NewXMLNode = XMLDoc.CreateNode(Xml.XmlNodeType.Element, "Node",
"Node", "")
XMLAttribute = XMLDoc.CreateAttribute("name")
XMLAttribute.Value = ChildNode.Text

NewXMLNode.Attributes.Append(XMLAttribute)
XMLNode.AppendChild(NewXMLNode)

SaveChildNodes(NewXMLNode, ChildNode, XMLDoc)
Next

End Sub
End Module
look on right side of website:
http://www.vbdotnetheaven.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top