3

The below code works fine with XML 1 but doesn't read rows from XML 2 (ROOT added). Do you know why?

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.async="false"
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("test.xml")

set  nodes=xmlDoc.SelectNodes("//customer")
for i=0 to nodes.length-1
set node = nodes(i)
set company = node.selectSingleNode("company")
msgbox company
next

XML 1:

<?xml version="1.0" encoding="UTF-8"?>
<customers>
    <customer>
        <name>ABCars</firma>
    </customer>
</customers>

XML 2:

<?xml version="1.0" encoding="UTF-8"?>
<ROOT xmlns="http://www.something.com ">
    <customers>
        <customer>
            <name>ABCars</firma>
        </customer>
    </customers>
</ROOT>
Przemek
  • 317
  • 2
  • 10

1 Answers1

3

It's because your second document has a default namespace. XPath is funky with default namespaces. You need either need to add a namespace prefix (e.g. xmlns:ns0="http://www.something.com" and then use that prefix (ns0:ROOT, ns0:customers, etc.), or refactor your XPath to use the local-name() function:

set nodes=xmlDoc.SelectNodes("//*[local-name()='customer']")

You'll also have to change your selectSingleNode:

set company = node.selectsingleNode("*[local-name()='company']")

If you search this site for "XPath default namespace" you'll find a lot of related questions.

Dan Field
  • 20,885
  • 5
  • 55
  • 71
  • Many thanks! One more thing - if I use the syntax: set nodes=xmlDoc.SelectNodes("//*[local-name(.) = 'customer']") how can I get customer name value? set company = node.selectSingleNode("name") doesn't seems to work any more. – Przemek Mar 31 '15 at 08:25
  • I've updated the answer. If this answers your question, please consider marking it as accepted by clicking the checkbox under it. – Dan Field Mar 31 '15 at 12:31