VB.Net Tutorial/XML/XML Tree
Load XML document to a TreeView
<source lang="vbnet">"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.rupiler " 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.ruponentModel.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. * " *************************************************************</source>
<source lang="vbnet">"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.Windows.Forms Imports System.Xml.XPath public class FrmPathNavigatorDemo
public Shared Sub Main Application.Run(New FrmPathNavigator) End Sub
End class Public Class FrmPathNavigator
Inherits Form " GroupBox contains Controls for locating XML file Friend WithEvents locateGroupBox As GroupBox Friend WithEvents cmdSelect As Button Friend WithEvents cboSelect As ComboBox Friend WithEvents txtSelect As TextBox " GroupBox contains Controls for navigating DOM tree Friend WithEvents navigateGroupBox As GroupBox Friend WithEvents cmdNext As Button Friend WithEvents cmdPrevious As Button Friend WithEvents cmdParent As Button Friend WithEvents cmdFirstChild As Button " TreeView displays DOM-tree results Friend WithEvents trePath As TreeView " navigator to traverse document Private xPath As XPathNavigator " references document for use by XPathNavigator Private document As XPathDocument " references TreeNode list used by TreeView control Private tree As TreeNode Public Sub New() MyBase.New() " This call is required by the Windows Form Designer. InitializeComponent() " Add any initialization after the " InitializeComponent() call " load in XML document document = New XPathDocument("YourFile.xml") " create nagivator xPath = document.CreateNavigator " create root node for TreeNodes tree = New TreeNode() tree.Text = xPath.NodeType.ToString " #root trePath.Nodes.Add(tree) " add tree " update TreeView control trePath.ExpandAll() trePath.Refresh() trePath.SelectedNode = tree " highlight root 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.ruponentModel.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.cboSelect = New System.Windows.Forms.ruboBox() Me.trePath = New System.Windows.Forms.TreeView() Me.navigateGroupBox = New System.Windows.Forms.GroupBox() Me.cmdFirstChild = New System.Windows.Forms.Button() Me.cmdParent = New System.Windows.Forms.Button() Me.cmdNext = New System.Windows.Forms.Button() Me.cmdPrevious = New System.Windows.Forms.Button() Me.txtSelect = New System.Windows.Forms.TextBox() Me.locateGroupBox = New System.Windows.Forms.GroupBox() Me.cmdSelect = New System.Windows.Forms.Button() Me.navigateGroupBox.SuspendLayout() Me.locateGroupBox.SuspendLayout() Me.SuspendLayout() " "cboSelect " Me.cboSelect.DropDownWidth = 121 Me.cboSelect.Items.AddRange(New Object() {"/sports", "/sports/game/name", "/sports/game/paragraph", "/sports/game [name="Cricket"]"}) Me.cboSelect.Location = New System.Drawing.Point(104, 32) Me.cboSelect.Name = "cboSelect" Me.cboSelect.Size = New System.Drawing.Size(224, 24) Me.cboSelect.TabIndex = 1 " "trePath " Me.trePath.FullRowSelect = True Me.trePath.HideSelection = False Me.trePath.ImageIndex = -1 Me.trePath.Location = New System.Drawing.Point(8, 272) Me.trePath.Name = "trePath" Me.trePath.SelectedImageIndex = -1 Me.trePath.Size = New System.Drawing.Size(336, 136) Me.trePath.TabIndex = 2 " "navigateGroupBox " Me.navigateGroupBox.Controls.AddRange(New System.Windows.Forms.Control() {Me.cmdFirstChild, Me.cmdParent, Me.cmdNext, Me.cmdPrevious}) Me.navigateGroupBox.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.navigateGroupBox.Location = New System.Drawing.Point(84, 144) Me.navigateGroupBox.Name = "navigateGroupBox" Me.navigateGroupBox.Size = New System.Drawing.Size(184, 120) Me.navigateGroupBox.TabIndex = 1 Me.navigateGroupBox.TabStop = False Me.navigateGroupBox.Text = "Navigation Controls" " "cmdFirstChild " Me.cmdFirstChild.Location = New System.Drawing.Point(104, 56) Me.cmdFirstChild.Name = "cmdFirstChild" Me.cmdFirstChild.TabIndex = 5 Me.cmdFirstChild.Text = "First Child" " "cmdParent " Me.cmdParent.Location = New System.Drawing.Point(8, 56) Me.cmdParent.Name = "cmdParent" Me.cmdParent.TabIndex = 4 Me.cmdParent.Text = "Parent" " "cmdNext " Me.cmdNext.Location = New System.Drawing.Point(56, 88) Me.cmdNext.Name = "cmdNext" Me.cmdNext.TabIndex = 3 Me.cmdNext.Text = "Next" " "cmdPrevious " Me.cmdPrevious.Location = New System.Drawing.Point(56, 24) Me.cmdPrevious.Name = "cmdPrevious" Me.cmdPrevious.TabIndex = 2 Me.cmdPrevious.Text = "Previous" " "txtSelect " Me.txtSelect.BackColor = System.Drawing.SystemColors.Info Me.txtSelect.Location = New System.Drawing.Point(8, 64) Me.txtSelect.Multiline = True Me.txtSelect.Name = "txtSelect" Me.txtSelect.ReadOnly = True Me.txtSelect.Size = New System.Drawing.Size(320, 56) Me.txtSelect.TabIndex = 2 Me.txtSelect.Text = "" " "locateGroupBox " Me.locateGroupBox.Controls.AddRange(New System.Windows.Forms.Control() {Me.txtSelect, Me.cmdSelect, Me.cboSelect}) Me.locateGroupBox.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.locateGroupBox.Location = New System.Drawing.Point(8, 8) Me.locateGroupBox.Name = "locateGroupBox" Me.locateGroupBox.Size = New System.Drawing.Size(336, 128) Me.locateGroupBox.TabIndex = 0 Me.locateGroupBox.TabStop = False Me.locateGroupBox.Text = "Locate Element" " "cmdSelect " Me.cmdSelect.Location = New System.Drawing.Point(8, 32) Me.cmdSelect.Name = "cmdSelect" Me.cmdSelect.TabIndex = 1 Me.cmdSelect.Text = "Select" " "FrmPathNavigator " Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(352, 413) Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.trePath, Me.navigateGroupBox, Me.locateGroupBox}) Me.Name = "FrmPathNavigator" Me.Text = "Path Navigator" Me.navigateGroupBox.ResumeLayout(False) Me.locateGroupBox.ResumeLayout(False) Me.ResumeLayout(False) End Sub
- End Region
" traverse to first child Private Sub cmdFirstChild_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdFirstChild.Click Dim newTreeNode As TreeNode If xPath.MoveToFirstChild Then newTreeNode = New TreeNode() " create new node DetermineType(newTreeNode, xPath) tree.Nodes.Add(newTreeNode) tree = newTreeNode " assign tree newTreeNode trePath.ExpandAll() trePath.Refresh() trePath.SelectedNode = tree Else Console.WriteLine("Current Node has no children.") End If End Sub " cmdFirstChild_Click Private Sub cmdParent_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdParent.Click If xPath.MoveToParent Then tree = tree.Parent Dim count As Integer = tree.GetNodeCount(False) Dim i As Integer For i = 0 To count - 1 tree.Nodes.Remove(tree.FirstNode) Next trePath.ExpandAll() trePath.Refresh() trePath.SelectedNode = tree Else Console.WriteLine("Current node has no parent.", "", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub " cmdParent_Click Private Sub cmdNext_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdNext.Click Dim newTreeNode As TreeNode = Nothing Dim newNode As TreeNode = Nothing If xPath.MoveToNext Then newTreeNode = tree.Parent " get parent node newNode = New TreeNode() " create new node DetermineType(newNode, xPath) newTreeNode.Nodes.Add(newNode) tree = newNode trePath.ExpandAll() trePath.Refresh() trePath.SelectedNode = tree Else Console.WriteLine("Current node is last sibling.", "", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub Private Sub cmdPrevious_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdPrevious.Click Dim parentTreeNode As TreeNode = Nothing If xPath.MoveToPrevious Then parentTreeNode = tree.Parent " get parent node " delete current node parentTreeNode.Nodes.Remove(tree) " move to previous node tree = parentTreeNode.LastNode " update TreeView control trePath.ExpandAll() trePath.Refresh() trePath.SelectedNode = tree Else " if current node has no previous siblings MessageBox.Show("Current node is first sibling.", "", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub " cmdPrevious_Click " process cmdSelect_Click event Private Sub cmdSelect_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdSelect.Click Dim iterator As XPathNodeIterator " enables node iteration " get specified node from ComboBox Try iterator = xPath.Select(cboSelect.Text) DisplayIterator(iterator) " print selection " catch invalid expressions Catch argumentException As System.ArgumentException MessageBox.Show(argumentException.Message, "Error", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub " cmdSelect_Click " print values for XPathNodeIterator Private Sub DisplayIterator( _ ByVal iterator As XPathNodeIterator) txtSelect.Clear() " prints selected node"s values While iterator.MoveNext txtSelect.Text &= iterator.Current.Value.Trim & vbCrLf End While End Sub " DisplayIterator " determine if TreeNode should display current node " name or value Private Sub DetermineType(ByVal node As TreeNode, _ ByVal xPath As XPathNavigator) " determine NodeType Select Case xPath.NodeType Case XPathNodeType.Element " if Element, get its name " get current node name, and remove whitespaces node.Text = xPath.Name.Trim Case Else " obtain node values " get current node value and remove whitespaces node.Text = xPath.Value.Trim End Select End Sub
End Class
" ************************************************************* " * (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. * " *************************************************************</source>