Load XML document to a TreeView : XML Tree « XML « VB.Net Tutorial






'Visual Basic.NET How to Program, Second Edition
'by Harvey M. Deitel (Author), Paul J. Deitel (Author), Tem R. Nieto (Author)
' Publisher: Prentice Hall; 2 edition (December 11, 2001)
' Language: English
' ISBN-10: 0130293636
' ISBN-13: 978-0130293633


Imports System.Xml
Imports System.Windows.Forms
Imports System.CodeDom.Compiler ' contains TempFileCollection


public class LoadXMLTreeView
   public Shared Sub Main
        Application.Run(New FrmXmlDom)
   End Sub
End class

Public Class FrmXmlDom
   Inherits Form

   ' TextBox and TreeView for displaying data
   Friend WithEvents txtConsole As TextBox
   Friend WithEvents treXml As TreeView

   ' Buttons for building, printing and reseting DOM tree
   Friend WithEvents cmdBuild As Button
   Friend WithEvents cmdPrint As Button
   Friend WithEvents cmdReset As Button

   Private source As XmlDocument ' reference to "XML document"

   ' reference copy of source's "XML document"
   Private copy As XmlDocument

   Private tree As TreeNode ' TreeNode reference

   Public Sub New()
      MyBase.New()

      ' This call is required by the Windows Form Designer.
      InitializeComponent()

      ' Add any initialization after the 
      ' InitializeComponent() call

      ' create XmlDocument and load letter.xml
      source = New XmlDocument()
      source.Load("YourFile.xml")

      ' initialize references to Nothing
      copy = Nothing
      tree = Nothing

   End Sub ' New

#Region " Windows Form Designer generated code "

   'Form overrides dispose to clean up the component list.
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      MyBase.Dispose(disposing)
   End Sub

   'Required by the Windows Form Designer
   Private components As System.ComponentModel.Container

   'NOTE: The following procedure is required by the Windows Form Designer
   'It can be modified using the Windows Form Designer.  
   'Do not modify it using the code editor.
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
      Me.treXml = New System.Windows.Forms.TreeView()
      Me.cmdBuild = New System.Windows.Forms.Button()
      Me.txtConsole = New System.Windows.Forms.TextBox()
      Me.cmdPrint = New System.Windows.Forms.Button()
      Me.cmdReset = New System.Windows.Forms.Button()
      Me.SuspendLayout()
      '
      'treXml
      '
      Me.treXml.ImageIndex = -1
      Me.treXml.Location = New System.Drawing.Point(8, 40)
      Me.treXml.Name = "treXml"
      Me.treXml.SelectedImageIndex = -1
      Me.treXml.Size = New System.Drawing.Size(344, 192)
      Me.treXml.TabIndex = 3
      '
      'cmdBuild
      '
      Me.cmdBuild.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.cmdBuild.Location = New System.Drawing.Point(8, 8)
      Me.cmdBuild.Name = "cmdBuild"
      Me.cmdBuild.Size = New System.Drawing.Size(104, 23)
      Me.cmdBuild.TabIndex = 0
      Me.cmdBuild.Text = "Build"
      '
      'txtConsole
      '
      Me.txtConsole.Location = New System.Drawing.Point(8, 240)
      Me.txtConsole.Multiline = True
      Me.txtConsole.Name = "txtConsole"
      Me.txtConsole.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
      Me.txtConsole.Size = New System.Drawing.Size(344, 96)
      Me.txtConsole.TabIndex = 4
      Me.txtConsole.Text = ""
      '
      'cmdPrint
      '
      Me.cmdPrint.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.cmdPrint.Location = New System.Drawing.Point(128, 8)
      Me.cmdPrint.Name = "cmdPrint"
      Me.cmdPrint.Size = New System.Drawing.Size(104, 23)
      Me.cmdPrint.TabIndex = 1
      Me.cmdPrint.Text = "Print"
      '
      'cmdReset
      '
      Me.cmdReset.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.cmdReset.Location = New System.Drawing.Point(248, 8)
      Me.cmdReset.Name = "cmdReset"
      Me.cmdReset.Size = New System.Drawing.Size(104, 23)
      Me.cmdReset.TabIndex = 2
      Me.cmdReset.Text = "Reset"
      '
      'FrmXmlDom
      '
      Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
      Me.ClientSize = New System.Drawing.Size(360, 341)
      Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.txtConsole, Me.treXml, Me.cmdReset, Me.cmdPrint, Me.cmdBuild})
      Me.Name = "FrmXmlDom"
      Me.Text = "Xml Dom"
      Me.ResumeLayout(False)

   End Sub

#End Region

   ' event handler for cmdBuild click event
   Private Sub cmdBuild_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles cmdBuild.Click

      ' determine if copy has been built already
      If Not copy Is Nothing Then
         Return ' document already exists
      End If

      ' instantiate XmlDocument and TreeNode
      copy = New XmlDocument()
      tree = New TreeNode()

      ' add root node name to TreeNode and add
      ' TreeNode to TreeView control
      tree.Text = source.Name ' assigns #root
      treXml.Nodes.Add(tree)

      ' build node and tree hierarchy
      BuildTree(source, copy, tree)
   End Sub ' cmdBuild_Click

   ' event handler for cmdPrint click event
   Private Sub cmdPrint_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles cmdPrint.Click

      ' exit if copy does not reference an XmlDocument
      If copy Is Nothing Then
         Return
      End If

      ' create temporary XML file
      Dim file As TempFileCollection = New TempFileCollection()

      ' create file that is deleted at program termination
      file.AddExtension("xml", False)
      Dim filename As String() = New String(0) {}
      file.CopyTo(filename, 0)

      ' write XML data to disk
      Dim writer As XmlTextWriter = _
        New XmlTextWriter(filename(0), _
        System.Text.Encoding.UTF8)

      copy.WriteTo(writer)
      writer.Close()

      ' parse and load temporary XML document
      Dim reader As XmlTextReader = _
         New XmlTextReader(filename(0))

      ' read, format and display data
      While reader.Read

         If reader.NodeType = XmlNodeType.EndElement Then
            txtConsole.Text &= "/"
         End If

         If reader.Name <> String.Empty Then
            txtConsole.Text &= reader.Name & vbCrLf
         End If

         If reader.Value <> String.Empty Then
            txtConsole.Text &= vbTab & reader.Value & vbCrLf
         End If

      End While

      reader.Close()
   End Sub ' cmdPrint_Click

   ' handle cmdReset click event
   Private Sub cmdReset_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles cmdReset.Click

      ' remove TreeView nodes
      If Not tree Is Nothing Then
         treXml.Nodes.Remove(tree)
      End If

      treXml.Refresh() ' force TreeView update

      ' delete XmlDocument and tree
      copy = Nothing
      tree = Nothing

      txtConsole.Clear() ' clear text box
   End Sub ' cmdReset_Click

   ' construct DOM tree
   Private Sub BuildTree(ByVal xmlSourceNode As XmlNode, _
      ByVal documentValue As XmlNode, _
      ByVal treeNode As TreeNode)

      ' create XmlNodeReader to access XML document
      Dim nodeReader As XmlNodeReader = _
         New XmlNodeReader(xmlSourceNode)

      ' represents current node in DOM tree
      Dim currentNode As XmlNode = Nothing

      ' treeNode to add to existing tree
      Dim newNode As TreeNode = New TreeNode()

      ' references modified node type for CreateNode
      Dim modifiedNodeType As XmlNodeType

      While nodeReader.Read

         ' get current node type
         modifiedNodeType = nodeReader.NodeType

         ' check for EndElement, store as Element
         If modifiedNodeType = XmlNodeType.EndElement Then
            modifiedNodeType = XmlNodeType.Element
         End If

         ' create node copy
         currentNode = copy.CreateNode(modifiedNodeType, _
            nodeReader.Name, nodeReader.NamespaceURI)

         ' build tree based on node type
         Select Case nodeReader.NodeType

            ' if Text node, add its value to tree
         Case XmlNodeType.Text
               newNode.Text = nodeReader.Value
               treeNode.Nodes.Add(newNode)

               ' append Text node value to currentNode data
               CType(currentNode, XmlText).AppendData _
                  (nodeReader.Value)

               documentValue.AppendChild(currentNode)

               ' if EndElement, move up tree
            Case XmlNodeType.EndElement
               documentValue = documentValue.ParentNode
               treeNode = treeNode.Parent

               ' if new element, add name and traverse tree
            Case XmlNodeType.Element

               ' determine if element contains content
               If Not nodeReader.IsEmptyElement Then

                  ' assign node text, add newNode as child
                  newNode.Text = nodeReader.Name
                  treeNode.Nodes.Add(newNode)

                  ' set treeNode to last child
                  treeNode = newNode

                  documentValue.AppendChild(currentNode)
                  documentValue = documentValue.LastChild

               Else ' do not traverse empty elements

                  ' assign NodeType string to newNode
                  newNode.Text = nodeReader.NodeType.ToString

                  treeNode.Nodes.Add(newNode)
                  documentValue.AppendChild(currentNode)
               End If

            Case Else ' all other types, display node type
               newNode.Text = nodeReader.NodeType.ToString
               treeNode.Nodes.Add(newNode)
               documentValue.AppendChild(currentNode)

         End Select

         newNode = New TreeNode()
      End While

      ' update TreeView control
      treXml.ExpandAll()
      treXml.Refresh()
   End Sub ' BuildTree

End Class ' FrmXmlDom

' *************************************************************
' * (C) Copyright 2002 by Deitel & Associates, Inc.           *
' *     and Prentice Hall.                                    *
' * All Rights Reserved.                                      *
' *                                                           *
' * DISCLAIMER: The authors and publisher of this book have   *
' * used their best efforts in preparing the book. These      *
' * efforts include the development, research, and testing of *
' * the theories and programs to determine their              *
' * effectiveness. The authors and publisher make no warranty *
' * of any kind, expressed or implied, with regard to these   *
' * programs or to the documentation contained in these books.*
' * The authors and publisher shall not be liable in any event*
' * for incidental or consequential damages in connection     *
' * with, or arising out of, the furnishing, performance, or  *
' * use of these programs.                                    *
' *************************************************************








25.6.XML Tree
25.6.1.Load XML document to a TreeView
25.6.2.XML path navigator