Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve the value of a XML attribute in VBS

<Requirement Description="description" Operation="Configure">
   <Action ID="1000" Name="Split">
     <Contract>
       <Parameter Name="Version">4</Parameter>
       <Parameter Name="DefaultServer">192.168.00.</Parameter>
       <Parameter Name="DefaultUser">administrator</Parameter>
       <Parameter Name="DefaultPassword">password</Parameter>
       <Parameter Name="DefaultDomain">192.168.00.00</Parameter>
       <Parameter Name="Split">1</Parameter>
     </Contract>
   </Action>
</Requirement>

From the above XML document my aim is to replace the IP address for both the attributes default server and default domain from a VBScript.

Set objXMLDoc = CreateObject("Microsoft.XMLDOM")
objXMLDoc.async = False
objXMLDoc.load(XMLFullPath) 
Set NodeList = objXMLDoc.documentElement.SelectNodes("//Parameter")

NodeList(i).nodeName 

Give name as Parameter and NodeList(i).Text gives me values like 4, IP address, administrator and others. But I am not able to get the attribute name so that I can directly change the value of the attribute.

like image 228
Vijay Nag Avatar asked Oct 15 '12 07:10

Vijay Nag


2 Answers

To answer your question, you can use the getAttribute function to access an attribute's value:

NodeList(i).getAttribute("Name")

You can also add a predicate to the XPath expression in your SelectNodes call to retrieve only the desired elements:

Set NodeList = objXMLDoc.documentElement.SelectNodes("//Parameter[@Name = 'DefaultServer' or @Name = 'DefaultDomain']")

This way, you don't have to retrieve and loop through the Parameter nodes that you're not interested in.

like image 146
Cheran Shunmugavel Avatar answered Oct 08 '22 19:10

Cheran Shunmugavel


A bit rusty, but I think you can use this to retrieve the nodevalue by nodename:

Function getTag(nList, nName)
    Dim i
    i = 0
    Do while i < nList.childNodes.length
        if (nList.childNodes(i).nodeName = nName) then
            getTag = nList.childNodes(i).childNodes(0).text
            Exit Function
        end if
        i = i + 1
    Loop
End Function

And to set it, probably

Sub setTag(nList, nName, val)
    Dim i
    i = 0
    Do while i < nList.childNodes.length
        if (nList.childNodes(i).nodeName = nName) then
            nList.childNodes(i).childNodes(0).text = val
            Exit Sub
        end if
        i = i + 1
    Loop
End Sub
like image 29
AardVark71 Avatar answered Oct 08 '22 18:10

AardVark71