Process All Nodes in a Document

Problem

You want to iterate through all nodes in an XML tree and display or modify the related information.

Solution

Create a generic procedure for processing the node, and call it recursively.

Discussion

The XmlDocument stores a tree of XmlNode objects. You can walk through this tree structure recursively to process every node.

For example, consider the following code, which displays information about every node in a document. A depth parameter tracks how many layers deep the nesting is and uses it to format the output with a variable-sized indent.

Public Module XmlOuputTest Public Sub Main() ' Load the document. Dim Doc As New XmlDocument Doc.Load("orders.xml") ' Start the node walk at the root node (depth = 0). DisplayNode(Doc.DocumentElement, ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.