Append a NodeList to a Node

Append a NodeList to a Node


Is it possible to append all the elements of a nodelist to a node as children without using a for loop? I want to overcome the performance problems incurred when using the for each loop in Visual Basic.


A node list is not a collection of nodes, although it may seem like it at first glance. Instead, a node list is a collection of pointers to nodes. This distinction may seem fairly trivial (and when enumerating across the items in a node list, it normally is), but things get more complicated when you attempt to do something like add a nodelist to a node in the same document. For example, if you create a nodelist like this:

set nodeList=xmlDoc.selectNodes("//*")

then each item in the nodelist is actually a pointer to a node somewhere within the tree. Appending this nodelist to a node would mean that a node could have as its grandfather itself, making navigation nightmarish. If, on the other hand, you want to add a nodelist to a node in a completely different XML tree, then when you iterate through the list and append the node, you are actually cloning the node implicitly (plus the node’s descendents). This cloning, not the for each loop, is probably what slows you down; cloning is a fairly expensive operation.

If you are working within VB, you can take a couple steps to speed things up within a node list’s for each loop. First, you should explicitly declare the looping variable as IXMLDOMNode. This has less overhead than an IXMLDOMElement, and you don’t have to go through an unnecessary conversion process from Node to Element for each loop. Also, unless you explicitly have to use descendents, explicitly clone the node without them, rather than making an implicit cloning. The function, AppendNodeList, incorporates both of these suggestions:

See also  Why ChatGPT Is So Important Today

sub AppendNodeList(parentNode as IXMLDOMNode, nodeList as _IXMLDOMNodeList,optional deep As Boolean= False)    dim node as IXMLDOMNode    for each node in nodeList       parentNode.appendChild node.cloneNode(deep)    nextend sub


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist