" Windows 窗體設計器生成代碼 " 節之後用以下示例代碼, 1 .vb 文件中替換整個代碼:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Initialize the controls and the form.
Label1.Text = "File Path"
Label1.SetBounds(8, 8, 50, 20)
TextBox1.Text = Application.StartupPath() & "/Sample.xml"
TextBox1.SetBounds(64, 8, 256, 20)
Button1.Text = "Populate the TreeView with XML"
Button1.SetBounds(8, 40, 200, 20)
Me.Text = "TreeView control from XML"
Me.Width = 336
Me.Height = 368
TreeView1.SetBounds(8, 72, 312, 264)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
' SECTION 1. Create a DOM Document and load the XML data into it.
Dim dom As New XmlDocument()
dom.Load(TextBox1.Text)
' SECTION 2. Initialize the treeview control.
TreeView1.Nodes.Clear()
TreeView1.Nodes.Add(New TreeNode(dom.DocumentElement.Name))
Dim tNode As New TreeNode()
tNode = TreeView1.Nodes(0)
' SECTION 3. Populate the TreeView with the DOM nodes.
AddNode(dom.DocumentElement, tNode)
TreeView1.ExpandAll()
Catch xmlEx As XmlException
MessageBox.Show(xmlEx.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub AddNode(ByRef inXmlNode As XmlNode, ByRef inTreeNode As TreeNode)
Dim xNode As XmlNode
Dim tNode As TreeNode
Dim nodeList As XmlNodeList
Dim i As Long
' Loop through the XML nodes until the leaf is reached.
' Add the nodes to the TreeView during the looping process.
If inXmlNode.HasChildNodes() Then
nodeList = inXmlNode.ChildNodes
For i = 0 To nodeList.Count - 1
xNode = inXmlNode.ChildNodes(i)
inTreeNode.Nodes.Add(New TreeNode(xNode.Name))
tNode = inTreeNode.Nodes(i)
AddNode(xNode, tNode)
Next
Else
' Here you need to pull the data from the XmlNode based on the
' type of node, whether attribute values are required, and so forth.
inTreeNode.Text = (inXmlNode.OuterXml).Trim
End If
End Sub
|