" 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
6.
按 F 5 键生成并运行应用程序。 确保 XML 文件路径是正确, 然后单击 按钮 。 XML 数据应显示在 TreeView 控件。
注意 : 资源可能是 URL 或一个 XML 流文件,。 指向了有关使用 XmlDocument 类来加载 XML 数据来自不同资源本文 " 参考 " 部分。
前面的代码示例映射 XML 树数据直接到 TreeView 并显示所有数据。 此外, 额外信息添加到显示或跳过不需要数据。 在许多情况, 可能要显示只属于 XML 数据。 动态数据, 要显示的部分可能构造, 结果是可扩展样式表语言 (XSL) 转换或 XPath 查询的结果。 本节介绍如何生成新 XML 文档只需节点, 然后将新文档添加到 TreeView 控件。 例如, 以下步骤通过 XPath 查询, 检索仅子元素的 originial XML 数据, 然后将此列表作为新节点添加到 TreeView 。
1.
粘贴以下代码之前前面示例中 TreeView1.ExpandAll 行:
' SECTION 4. Create a new TreeView Node with only the child nodes.
Dim nodelist As XmlNodeList = dom.SelectNodes("//child")
Dim cDom As New XmlDocument()
cDom.LoadXml("<children></children>")
Dim node As XmlNode
For Each node In nodelist
Dim newElem As XmlNode = cDom.CreateNode(XmlNodeType.Element, node.Name, node.LocalName)
newElem.InnerText = node.InnerText
cDom.DocumentElement.AppendChild(newElem)
Next
TreeView1.Nodes.Add(New TreeNode(cDom.DocumentElement.Name))
tNode = TreeView1.Nodes(1)
AddNode(cDom.DocumentElement, tNode)