reading xml file with vbscript
Asked Answered
G

2

7

I am trying to write a vbscript to automate the configuration of a storage array. I'm having some difficulty figuring out how best to navigate the XML.

An example section of my 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>

So I want to iterate through each interface (there is 5 in reality) and set the appropriate IP and netmask on the correct interface.

I'm currently doing this:

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

but there must be a cleaner way do doing this where I can select the interface section and read in the port, ipaddress & netmask, issue the command and then move into the next interface?

Thanks.

Gilbertgilberta answered 24/11, 2011 at 9:17 Comment(0)
W
6

First approach:

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
Waers answered 24/11, 2011 at 9:32 Comment(0)
S
2

This works for me:

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
Salmi answered 4/3, 2016 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.