VBScript XMLDOM
问题描述:
我想从XMLDOM的VBScript中检索下面的XML中的所有值。不幸的是,这些节点没有相同的名称标签,并且标签数量(c[n]
)是可变的。我如何读取字典中的值?VBScript XMLDOM
我可以用得到的标签:
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "false"
xmlDoc.Load(xmlhttp.responseXML)
Set values = xmlDoc.getElementsByTagName("header")
如何迭代的<header>
所有子节点?
<table>
<header>
<c0 type="string">name</c0>
<c1 type="ip_address">last_ip_address</c1>
<c2 type="string">group_name</c2>
<c3 type="enum">device_type</c3>
<c4 type="string">os_version_and_architecture</c4>
<c5 type="string">device_manufacturer</c5>
<c6 type="integer">number_of_cpus</c6>
<c7 type="string">cpu_model</c7>
<c8 type="integer">number_of_cores</c8>
<c9 type="mhz">cpu_frequency</c9>
<c10 type="byte">total_ram</c10>
<c11 type="integer">number_of_graphical_cards</c11>
<c12 type="byte">graphical_card_ram</c12>
<c13 type="datetime">last_system_boot</c13>
<c14 type="datetime">last_logon_time</c14>
<c15 type="string">bios_serial_number</c15>
<c16 type="string">device_product_version</c16>
</header>
</table>
答
使用Msxml2.DOMDocument
代替弃用Microsoft.XMLDOM
,并使用SelectNodes()
与XPath表达式代替getElementsByTagName()
。
Set d = CreateObject("Scripting.Dictionary")
For Each n In xmlDoc.SelectNodes("//table/header/*")
d.Add n.NodeName, n.Text
Next
答
你可以给这个代码试试:
Set xobj = CreateObject("MSXML2.DomDocument")
xobj.async=False
xmlDoc.Load(xmlhttp.responseXML)
Set header = xobj.selectnodes("//header")
Set children = header.item(0).childNodes 'Only the child nodes of first header node. You can easily run a loop to fetch all the headers' childnodes
Set objD = CreateObject("scripting.dictionary")
For Each child In Children
objD.Add child.nodeName, child.text 'Adding childnode's values to the dictionary; childnode's tagname being the key for each element in dictionary
Next
a=objD.items
For i=0 To UBound(a)
MsgBox a(i) 'Displaying the dictionary values
next
Set objD = Nothing
Set xobj=Nothing