接著,在Form_Load事件中添加如下的代碼:
Private Sub Form_Load()
Dim objDOM As DOMDocument
Set objDOM = New DOMDocument
Call objDOM.loadXML( _
"
Call AddNode(objDOM.documentElement, Nothing)
Set objDOM = Nothing
End Sub
以上代碼建立并傳入XML,然后調(diào)用AddNode方法。它包含兩個(gè)變量:添加的XML節(jié)點(diǎn),添加的TreeView節(jié)點(diǎn)。AddNode方法第一次被調(diào)用,"Nothing"被傳遞到TreeNode變量。
Private Sub AddNode(ByRefXMLNode As IXMLDOMNode, ByRefTreeNode As Node)
Dim objNode As Node
Dim xmlNodeList As IXMLDOMNodeList
Dim lngNodeIndex As Long
On Error GoTo ERR_HANDLER
If TreeNode Is Nothing Then
Set objNode = TreeView1.Nodes.Add
Else
Set objNode = TreeView1.Nodes.Add(TreeNode, tvwChild)
End If
objNode.Text = XMLNode.nodeName
objNode.Expanded = True
注釋:== Add child nodes
Set xmlNodeList = XMLNode.childNodes
For lngNodeIndex = 0 To xmlNodeList.length - 1
Call AddNode(xmlNodeList.Item(lngNodeIndex), objNode)
Next lngNodeIndex
ERR_HANDLER:
If Err.Number <> 0 Then
MsgBoxErr.Description
End If
End Sub
首先AddNode方法添加一個(gè)新的節(jié)點(diǎn)到樹形控件,然后將節(jié)點(diǎn)的文本傳遞給XML節(jié)點(diǎn)的名稱。如果XML節(jié)點(diǎn)包含有子節(jié)點(diǎn),AddNode方法則遞進(jìn)地添加子節(jié)點(diǎn),直到所有子節(jié)點(diǎn)被傳遞。