xmlvbscriptselectsinglenode

Select Single Node with a attribute name in vbscript


Have an xml file

<DataSource>
     <localdata>
        <add context="Localization">
           <parameter name="timeout" type="int" defaultvalue="60"/>
           <parameter name="address" type="string" defaultvalue="192.168.9.45" />
           <parameter name="port" type="int" defaultvalue="6789"/>
        </add>
       <add context="General">
           <parameter name="timeout" type="int" defaultvalue="60"/>
           <parameter name="address" type="string" defaultvalue="192.168.9.478" />
           <parameter name="port" type="int" defaultvalue="5674"/>
        </add>
    </localdata>
   </DataSource>

I need to get the element whose attribute is context="General" using vbscript

I can get the top node with this statement

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.load("DataConfiguration.xml")
Set queryNode = xmlDocument.selectSingleNode(".//localdata")

But not sure how to extend this.

Any help is appreciated.

Thanks in advance.


Solution

  • To get any node, you can use this

    Set queryNode = xmlDocument.selectSingleNode(".//node()[@context = 'General']")
    

    or, specifically for the add node

    Set queryNode = xmlDocument.selectSingleNode(".//add[@context = 'General']")
    

    This is using XPath, which may require you to set the selection namespace property of the DomDocument

    xmlDocument.setProperty "SelectionLanguage", "XPath"
    

    You might want to search for a XPath tutorial, such as w3schools - New Link