Insert Nodes in an XML Document

Problem

You need to modify an XML document by inserting new data.

Solution

Create the node using the appropriate XmlDocument method (such as CreateElement, CreateAttribute, CreateNode, and so on). Then insert it using the appropriate XmlNode method (such as InsertAfter, InsertBefore, or AppendChild).

Discussion

Inserting a node is a two-step process. You must first create the node, and then you insert it in the appropriate location. Optionally, you can then call XmlDocument.Save to persist changes to a file.

To create a node, you use one of the XmlDocument methods that starts with the word Create, depending on the type of node. This ensures that the node will have the same namespace as the rest of the document. Next you ...

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.