Share via


Create New Nodes in the DOM

The XmlDocument has a Create method for all of the node types. Supply the method with a name when required, and content or other parameters for those nodes that have content, for example a text node, and the node will be created. The following methods are ones that need a name, and a few other parameters filled to create an appropriate node.

  • CreateComment
  • CreateCDataSection
  • CreateDocumentFragment
  • CreateDocumentType
  • CreateElement
  • CreateProcessingInstruction
  • CreateTextNode
  • CreateXmlDeclaration
  • CreateWhitespace
  • CreateSignificantWhitespace

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 will appear in the DOM.

Method Node placement
InsertBefore Inserted before the reference node. For example, to insert the new node in position 5:
Dim refChild As XmlNode = node.ChildNodes(4)
'The reference is zero-based.node.InsertBefore(newChild, refChild);
[C#]
XmlNode refChild = node.ChildNodes[4];
//The reference is zero-based.
node.InsertBefore(newChild, refChild); 

For more information, see XmlNode.InsertBefore Method.

InsertAfter Inserted after the reference node. For example:
node.InsertAfter(newChild, refChild)
[C#]
node.InsertAfter(newChild, refChild); 

For more information, see XmlNode.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 XmlNode.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 XmlNode.PrependChild Method.
Append Appends an XmlAttribute node to the end of the attribute collection associated with an element. For more information, see XmlAttributeCollection.Append Method.

See Also

XML Document Object Model (DOM)