Search code examples
xmlvbamsxml

How do I iterate over a node's child nodes after selecting it with selectSingleNode


I am trying to select a single node from an XML document with selectSingleNode() and then use selectNodes on that node to further select child items of that node:

option explicit

sub main() ' {

   dim doc as new MSXML2.DOMDocument

   doc.loadXML(                                                                                     _
     "<items>"                                                                                    & _
     "  <item id='1000'><name val='ABC'/><name val='DEF'/><name val='GHI'/><foo>xxx</foo></item>" & _
     "  <item id='1001'><name val='JKL'/><name val='MNO'/><name val='PQR'/><bar>yyy</bar></item>" & _
     "  <item id='1002'><name val='STU'/><name val='VWX'/><name val='YZ.'/><baz>zzz</baz></item>" & _
     "</items>")

    dim item as msxml2.IXMLDOMElement
    set item = doc.selectSingleNode("//item[@id='1002']")

    dim names as msxml2.IXMLDOMSelection
    set names = item.selectNodes("//name")

    dim name as msxml2.IXMLDOMElement
    for each name in names
        debug.print(name.getAttribute("val"))
    next name

end sub ' }

I have expected this piece of code to print the Attribute values STU, VWX and YZ.. However, when running it, it prints each <name>'s val value.

Apparently, selectNodes() selects all nodes from the root document.

I don't understand why this is and how I can get the real child nodes of a previously selected node.


Solution

  • Change

    Set names = item.selectNodes("//name")
    

    To

    Set names = item.SelectNodes("name")