Search code examples
xmlxpathvb6msxml

How can I efficiently select child elements by name, using XPath?


I have a legacy VB6 program and a need to parse XML. Through reading several related topics in this excellent site, I have found that using MSXML dll is the way to load the XML and be able to parse it. I have also attempted to browse the MSDN MSXML documentation to find my answer, but am finding it difficult. I feel the answer is easy but some pointers would go a long way.

For example, here is the gist of my XML structure:

<response>
  <header>
    : :
  </header>
  <result>
    <record>
      <data1>some text</data1>
      <data2>some text</data2>
        :   :
      <dataN>some text</dataN>
    </record>
     : : multiple records with data
  </result>
</response>

I want to process all Records, and extract just certain Data children By Name from each.

I know how to get a IXMLDOMNodeList from the document to get the records, but not sure of the optimum way to get the data rows By Name on each record. Here is my VB6 code.

Dim doc as New MSXML2.DOMDocument

if doc.Load(myURL) Then
  Dim nodeList as MSXML2.IXMLDOMNodeList, node as MSXML2.IXMLDOMNode

  Set nodeList = doc.selectNodes("/response/result/record")
  For Each node in nodeList
    'How do I get the child element with name "data2" from the list of children?
  Next node
end if

Inside that For/Each loop for each record, I want to access the child Element with name of "dataN" for example. I know I can loop through node.childNodes and check to see if childNode(i).baseName = "dataN", but that seems inefficient. But I can't seem to find a method that allows me to find these child nodes by name.

Like I said, probably a simple answer, but I can't seem to find the best practice for this from similar posts on this site or in the MSXML documentation.

Thanks.


Solution

  • Continue to use XPath e.g. node.selectSingleNode("data2").text inside the For Each gives you a string with the text contents of the data2 element.