I am trying to take the value of TemplatePath" /> I am trying to take the value of TemplatePath" /> I am trying to take the value of TemplatePath"/>

How to read xml file?

203 views Asked by At

Sample XML file (insert path):

<FilePath>
<TemplatePath> "C:\Users\test.txt" </TemplatePath>
</FilePath>

I am trying to take the value of TemplatePath.

I get

run-time error '91'

Sub testxml()

Set oXMLFile = CreateObject("Microsoft.XMLDOM")
oXMLFile.Load ("C:\Users\Config.xml")

Set prova = oXMLFile.SelectNodes("//FilePath/TemplatePath").item(0).Text
Debug.Print prova

I cannot find proper documentation. Microsoft learn doesn't explain well.

2

There are 2 answers

0
Alex K. On BEST ANSWER

Set prova = is incorrect as .Text returns a string not an object reference, instead:

dim text as string
text = oXMLFile.SelectNodes("//FilePath/TemplatePath").Item(0).Text

Alternatively if there is always a single TemplatePath element simply:

debug.print oXMLFile.SelectSingleNode("//FilePath/TemplatePath").Text

If there are multiple nodes, loop them:

Set prova = oXMLFile.SelectNodes("//FilePath/TemplatePath")
   
For Each node In prova
    debug.print node.Text
Next node
0
Eugene Astafiev On

You may find the XML DOM Methods described in MSDN.

To read the content you may use the following code (without item[0]):

oXMLFile.SelectSingleNode("//FilePath/TemplatePath").Text