通过VBA导入XML,访问属性

时间:2015-08-19 09:58:06

标签: xml vba nodes

XML示例:



<User id='user1'>
	<Attribute name='firstname' value='Testname'/>
	<Attribute name='lastname' value='Testname'/>
	<Attribute name='id' value='userid'/>
</User>
<User id='user2'>
	<Attribute name='firstname' value='Testname'/>
	<Attribute name='lastname' value='Testname'/>
	<Attribute name='id' value='userid'/>
</User>
&#13;
&#13;
&#13;

我想通过VBA提取当前用户的firstname,lastname,id。

VBA片段:

Dim xmlDoc As MSXML2.DOMDocument
Dim xmlElement As MSXML2.IXMLDOMElement
Dim xmlSelection As MSXML2.IXMLDOMSelection

Set xmlDoc = New MSXML2.DOMDocument
xmlDoc.async = False
xmlDoc.Load strUrl

Set xmlSelection = xmlDoc.SelectNodes("PATH TO XML")

For Each xmlElement In xmlSelection
    Debug.Print xmlElement.getAttribute("name")
    >>> how do I debug print the attributes firstname, lastname, name?! I need the values <<<

Next xmlElement

提前致谢!

1 个答案:

答案 0 :(得分:0)

您无法直接打印对象,但可以打印其子文本字符串  代替。

看来您的XML不是一个完整的XML,而是它的一部分,对吧?我只使用一个节点作为示例的根节点。

Set Nodes = xmlDoc.SelectNodes("//User")
For Each Node In Nodes
    For i = 0 To Node.childNodes.Length - 1
        ' Print Attribute Name
        Debug.Print Node.childNodes(i).Attributes(0).Text
        ' Print Attribute Value
        Debug.Print Node.childNodes(i).Attributes(1).Text
    Next i
Next Node
相关问题