2011-11-24 158 views
5

我想寫一個vbscript來自動配置存儲陣列。我在理解如何最好地導航XML時遇到了一些困難。用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 

但必須有不這樣做,我可以選擇的接口部分,將端口讀取更清潔的方式,ip地址&網絡掩碼,發出命令,然後進入下一個界面?

謝謝。

回答

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

這個工作對我來說:

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