1

Is it possible to combine two groups of objects in VBA? I was trying to combine the two groups of elements obtained via getelementsbytagname

so something like below

Set a = oXMLFile.getElementsByTagName(tag1)
Set b = oXMLFile.getElementsByTagName(tag2)

c = union(a,b)

Anyone can help?

Community
  • 1
  • 1
Timescape
  • 47
  • 8

1 Answers1

0

You could write an XPath expression that is a union of both tag names and feed that into .selectNodes That will give you an IXMLDOMNodeList with all of the element nodes which have either tag.

If you wanted every element node called "foo" and every element node called "bar" then this should work (the | symbol is the union operator in XPath):

Set listOfBothTags = domDoc.selectNodes("//foo | //bar")

Notes:

  • the nodes will be returned in the order they appear in the document so you will get nodes of both tags mixed throughout the collection. In XPath 2.0 and later. this can be avoided by using the , operator but MSXML2 only supports XPath 1.0
  • using // like this isn't very efficient so using a more specific query (e.g. "/fee/fi/foo | /fee/fi/bar") is preferable on larger documents
  • the DOM document should be declared as "DOMDocument60" (early binding) or created as "DOMDocument.6.0" (late binding) Older versions of the MSXML2 DOMDocument used XSL Patterns as the query language rather than XPath but you can override this as described here
barrowc
  • 10,444
  • 1
  • 40
  • 53
  • Thanks tons barrowc! The | symbol works like a charm! I have one more quick question. Is is possible to select all nodes with tags containing specific string? e.g. I want to select all nodes with tags containing "foo". so both "foObar" and "xyzFOOxyz" will be picked up. – Timescape Nov 22 '15 at 07:39
  • Try `Set nodeList = domDoc.SelectNodes("//*[contains(name(), 'foo')]")` as described in [this question](http://stackoverflow.com/q/2691426/2127508) and in the XPath 1.0 specification [here](http://www.w3.org/TR/xpath/#function-name) and [here](http://www.w3.org/TR/xpath/#function-contains). If you require case-insensitive matching then see [this answer](http://stackoverflow.com/a/1625859/2127508) – barrowc Nov 22 '15 at 15:05
  • This is fantastic barrowc! Thanks for your help! – Timescape Nov 23 '15 at 01:38