Retrieve the value of a XML attribute in VBS
Asked Answered
A

2

5
<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.

Adlai answered 15/10, 2012 at 7:51 Comment(0)
H
6

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.

Hagiolatry answered 16/10, 2012 at 5:35 Comment(1)
getAttribute("") was something I was missing on one of my scripts. thanks for the reference.Radiocommunication
W
2

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
Waxwork answered 15/10, 2012 at 8:19 Comment(2)
set obj = NodeList(i).attributes this gives all the values of the attributes. Thanks anyways :)Adlai
Ohhh... banging my head against the desk now that I didn't read your question more carefully.Waxwork

© 2022 - 2024 — McMap. All rights reserved.