Retrieve the value of a XML attribute in VBS

Vijay Nag picture Vijay Nag · Oct 15, 2012 · Viewed 28.9k times · Source
<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.

Answer

Cheran Shunmugavel picture Cheran Shunmugavel · Oct 16, 2012

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.