XML Node Counting in MS Access VBA

vadao
vadao used Ask the Experts™
on
How would I go about counting the number of nodes for a loaded XML document using MSXML2.DOMDocument60 in MS access VBA without using Xpath? I have tried the getelementsByTagName but I keep getting an error.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2014

Commented:
There is a count property on node collections, such as children.  Have you iterated the parents and their children, getting the counts?  This would seem to be the fastest, but depends on your knowledge of the XML document, the document's variability, and depth.

Alternatively, you might iterate every node, keeping a tally of nodes as you traverse the tree.
Mark WillsTopic Advisor, Page Editor
Distinguished Expert 2018

Commented:
aikimark is correct, you can count nodes...

Something like :
Dim objxmldoc As New MSXML2.DOMDocument60
Dim MyCount As MSXML2.IXMLDOMNodeList

open/load/namespace etc...

Set MyCount = objxmldoc.selectNodes("//ns1:yourtagtocount")

Open in new window

It would help if we could see your code so far...
Senior Developer
Commented:
What have you tried exactly?

Option Compare Database
Option Explicit

Public Sub TestCountGetElementsByTagName()

  'Using reference to MSXML2.
  Dim document As MSXML2.DOMDocument60
  
  Set document = New MSXML2.DOMDocument60
  document.LoadXML "<root><a>1</a><a>2</a><b><a>3</a></b></root>"
  Debug.Print document.getElementsByTagName("a").Length
  Set document = Nothing
   
End Sub

Open in new window

Top Expert 2014

Commented:
Tweaking Ste5an's code...
Public Function GetCountOfNodesByTagNameList(ByVal parmXMLString, ByVal parmNodeTagList, Optional parmDelim = "^") As Long
    Dim oDoc As Object
    Dim vTag As Variant
    Dim lngCount As Long
    Set oDoc = CreateObject("MSXML2.DOMDocument")
    oDoc.LoadXML parmXMLString
    For Each vTag In Split(parmNodeTagList, parmDelim)
        lngCount = lngCount + oDoc.getElementsByTagName(vTag).Length
    Next
    Set oDoc = Nothing
    GetCountOfNodesByTagNameList = lngCount
End Function

Open in new window

Example of invoking the function, looking for nodes "a" and "b" and "root"
?GetCountOfNodesByTagNameList("<root><a>1</a><a>2</a><b><a>3</a></b></root>","a^b^root")
 5 

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial