TechMatt__
TechMatt__

Reputation: 31

How to read xml file?

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.

Upvotes: 0

Views: 382

Answers (2)

Eugene Astafiev
Eugene Astafiev

Reputation: 49395

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

Upvotes: 1

Alex K.
Alex K.

Reputation: 175816

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

Upvotes: 1

Related Questions