selectSingleNode using vbscript

Maan Dim picture Maan Dim · Oct 5, 2013 · Viewed 11.2k times · Source

Below is the structure of my xml file:

<configuration>
  <appSettings>
    <add key="ProductVersion" value="5.5.5"/>
    <add key="LogsDirectory" value="e:\\Logs"/>
  </appSettings>
<configuration>

I am trying following code to get value of LogsDirectory:

configurationFilePath = "e:\conf.xml"
Set xmlDoc = CreateObject("MSXML2.DomDocument.6.0")
xmlDoc.async = false
Call xmlDoc.load(configurationFilePath)

xpath1 = ".//configuration/appSettings/add[@key='LogsDirectory']/@value"
LogsDirectory = xmlDoc.selectSingleNode(xpath1)

But it is giving error as object required.

Any help highly appreciated.

Thanks

Answer

Ekkehard.Horner picture Ekkehard.Horner · Oct 5, 2013

People who not use an error checking skeleton for XML work like this:

Option Explicit

Dim oFS    : Set oFS   = CreateObject("Scripting.FileSystemObject")
Dim sFSpec : sFSpec    = oFS.GetAbsolutePathName(".\19194544.xml")
Dim oXDoc  : Set oXDoc = CreateObject("MSXML2.DomDocument.6.0")
oXDoc.setProperty "SelectionLanguage", "XPath"
oXDoc.async = False
oXDoc.load sFSpec

If 0 = oXDoc.ParseError Then
   WScript.Echo sFSpec, "looks ok"
   Dim sXPath
   For Each sXpath In Array( _
       ".//configuration/appSettings/add[@key='LogsDirectory']/@value" _
   )
       Dim ndFnd : Set ndFnd = oXDoc.selectSingleNode(sXpath)
       If Not ndFnd Is Nothing Then
          WScript.Echo "found |" & ndFnd.xml & "|"
       Else
          WScript.Echo "not found |" & sXPath & "|"
       End If
   Next
Else
   WScript.Echo oXDoc.ParseError.Reason
End If

also do bungee jumping without ropes.

In your case the .ParseError.Reason

The following tags were not closed: configuration, configuration.

explains why there is no document to search in. At least this spares you the error you'd get when you try to assign the node returned from .selectSingleNode() to LogsDirectory without using Set.