VBScript XMLDOM

VBScript XMLDOM

我正在尝试使用 XMLDOM 在 VBScript 中检索下面 XML 中的所有值。不幸的是,节点没有相同的名称标签,标签的数量 (c[n]) 是可变的。如何将值读入字典?

我可以使用以下方法获取标签:

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