1

我有一个具有以下结构的 xml 文件:

<table name="tblcats">
    <row>
        <Id>3680</Id>
        <Industry>Associations</Industry>
        <ParentId>1810</ParentId>
    </row>
    <row>
        <Id>1592</Id>
        <Industry>Fortune 100</Industry>
        <ParentId>1810</ParentId>
    </row>
    <row>
        <Id>1601</Id>
        <Industry>Oil &amp; Gas Operations</Industry>
        <ParentId>1689</ParentId>
    </row>
    <row>
</table>

我想使用这个 XML 文件创建一个树视图。我写了以下代码

   ' Load a TreeView control from an XML file.
    Private Sub LoadTreeViewFromXmlFile(ByVal file_name As String, ByVal trv As TreeView)
        ' Load the XML document.
        Dim xml_doc As New XmlDocument
        xml_doc.Load(file_name)

        ' Add the root node's children to the TreeView.
        trv.Nodes.Clear()
        trv.Nodes.Add(New TreeNode(xml_doc.DocumentElement.Name))
        AddTreeViewChildNodes(trv.Nodes, xml_doc.DocumentElement)
    End Sub

    ' Add the children of this XML node 
    ' to this child nodes collection.
    Private Sub AddTreeViewChildNodes(ByVal parent_nodes As TreeNodeCollection, ByVal xml_node As XmlNode)
        For Each child_node As XmlNode In xml_node.ChildNodes
            ' Make the new TreeView node.
            Dim new_node As TreeNode = New TreeNode(child_node.Item("Industry").InnerText, child_node.Item("Id").InnerText)

            parent_nodes.Add(new_node)

        Next child_node
    End Sub

但它会创建一个像这样的树视图:

->table
->Associations
->Fortune 100

我希望表格作为这样的父元素

->table
  ->Associations
  ->Fortune 100

这样如果我单击表节点,所有树都会折叠或展开。请建议我该如何解决

4

1 回答 1

0

问题是您将树视图控件本身传递给 AddTreeViewChildNodes 方法,因此它将所有节点添加到同一顶层。您需要将创建的根节点传递给该方法,以便在其下添加子节点。

改变:

    trv.Nodes.Add(New TreeNode(xml_doc.DocumentElement.Name))
    AddTreeViewChildNodes(trv.Nodes, xml_doc.DocumentElement)

到:

    Dim rootNode As TreeNode = New TreeNode(xml_doc.DocumentElement.Name)
    trv.Nodes.Add(rootNode)
    AddTreeViewChildNodes(rootNode, xml_doc.DocumentElement)
于 2012-05-15T18:29:00.337 回答