xmlvbaxmldom

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.


Solution

  • 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