我知道如何使用XML节点来构建树视图但是我不确定如何使用仅在XML文件的某个父节点下找到的节点填充树视图。
示例:
我希望树视图只显示节点TreeViewItems下列出的节点...而忽略...
<MyXmlFile>
<AllOtherStuff>
<bla1>blabla<Bla1>
<bla2>blablabla<Bla2>
<bla3>blablablabla<Bla3>
</AllOtherStuff>
<TreeviewItems>
<item1>DWG file</item1>
<item2>DOC file</item2>
<item3>PDF file</item3>
</TreeviewItems>
</MyXmlFile>
以下是我用于使用XML文件的全部内容填充树视图的代码...
Dim xmldoc As New XmlDataDocument()
Dim xmlnode As XmlNode
Dim fs As New FileStream("tree.xml", FileMode.Open, FileAccess.Read)
xmldoc.Load(fs)
xmlnode = xmldoc.ChildNodes(1)
TreeView1.Nodes.Clear()
TreeView1.Nodes.Add(New TreeNode(xmldoc.DocumentElement.Name))
Dim tNode As TreeNode
tNode = TreeView1.Nodes(0)
AddNode(xmlnode, tNode)
EDDIT:
Private Sub AddNode(ByVal inXmlNode As XmlNode, ByVal inTreeNode As TreeNode)
Dim xNode As XmlNode
Dim tNode As TreeNode
Dim nodeList As XmlNodeList
Dim i As Integer
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
inTreeNode.Text = inXmlNode.InnerText.ToString
End If
End Sub
答案 0 :(得分:0)
像
这样的东西 xmldoc.DocumentElement.SelectSingleNode("TreeviewItems")
将为您提供节点,然后只为其子女做一个foreach。