用vbscript读取xml文件

时间:2011-11-24 09:17:42

标签: xml vbscript xmldom

我正在尝试编写一个vbscript来自动配置存储阵列。我很难弄清楚如何最好地导航XML。

我的XML的示例部分:

<SERVER>
<INTERFACE>
<PORT>0</PORT>
<IPADDRESS>192.168.1.1</IPADDRESS>
<NETMASK>255.255.255.0</NETMASK>
</INTERFACE>
<INTERFACE>
<PORT>1</PORT>
<IPADDRESS>192.168.1.2</IPADDRESS>
<NETMASK>255.255.255.0</NETMASK>
</INTERFACE>
</SERVER>

所以我想迭代每个接口(实际上有5个)并在正确的接口上设置适当的IP和网络掩码。

我目前正在这样做:

Set objXMLDoc = CreateObject("Microsoft.XMLDOM") 
objXMLDoc.async = False 
objXMLDoc.load("example.xml")

Set Root = objXMLDoc.documentElement 
Set NodeList = Root.getElementsByTagName("interface") 
port = 0
For Each Elem In NodeList 
WScript.Echo "Port " & port & " has IP address of " & Elem.text
port = port + 1
Next

但是必须有一个更干净的方法来做这个,我可以选择接口部分并读入端口,ipaddress&amp; netmask,发出命令,然后进入下一个界面?

感谢。

2 个答案:

答案 0 :(得分:5)

第一种方法:

For Each Elem In NodeList 
   SET port = Elem.getElementsByTagName("Port")(0)
   SET ip = Elem.getElementsByTagName("IPADDRESS")(0)
   WScript.Echo "Port " & port.nodeValue & " has IP address is " & ip.nodeValue
Next

答案 1 :(得分:1)

这对我有用:

sub main
    Set nodeList = xmlDoc.documentElement.selectNodes("//interface")

    For Each node in nodeList
        handleNode(node)
    Next
end sub

sub handleNode(node)
    Dim port, ipaddress, netmask, attribute

    For each elem in node.childNodes
        Select Case node.tagName
            Case "port"
                port = elem.text
            Case "ipaddress"
                ipaddress = elem.text
            Case "netmask"
                netmask = elem.text
            Case "tag with attributes"
                attribute = elem.getAttribute("attributeName")
        End Select
    Next

    WScript.Echo "Port " & port & " has IP address of " & ipaddress & " and useful attribute " & attribute

end sub