Create New Nodes in the DOM

The XmlDocument class has a create method for all of the node types. To create a node, supply the method with a name, when required, and content or other parameters for those nodes that have content (for example, a text node). The following methods need a name and a few other parameters filled to create an appropriate node:

Other node types have more requirements than just providing data to parameters.

For information on attributes, see Creating New Attributes for Elements in the DOM. For information on element and attribute name validation, see XML Element and Attribute Name Verification when Creating New Nodes. For creating entity references, see Creating New Entity References. For information on how namespaces affect the expansion of entity references, see Namespace Affect on Entity Reference Expansion for New Nodes Containing Elements and Attributes.

Once new nodes are created, there are several methods available to insert them into the tree. The table lists the methods with a description of where the new node appears in the XML Document Object Model (DOM).

Method Node placement
InsertBefore Inserted before the reference node. For example, to insert the new node in position 5:

XmlNode refChild = node.ChildNodes[4]; // The reference is zero-based.

node.InsertBefore(newChild, refChild);

For more information, see the InsertBefore method.
InsertAfter Inserted after the reference node. For example:

node.InsertAfter(newChild, refChild);

For more information, see the InsertAfter method.
AppendChild Adds the node to the end of the list of child nodes for the given node. If the node being added is an XmlDocumentFragment, the entire contents of the document fragment are moved into the child list of this node. For more information, see the AppendChild method.
PrependChild Adds the node to the beginning of the list of child nodes of the given node. If the node being added is an XmlDocumentFragment, the entire contents of the document fragment are moved into the child list of this node. For more information, see the PrependChild method.
Append Appends an XmlAttribute node to the end of the attribute collection associated with an element. For more information, see the Append method.

See also