Replacing the XmlNode s within an XmlDocumentUsing the insertion methods is not the only way to insert nodes into an XmlDocument . You can also insert new nodes by replacing nodes that already exist in the node tree by using the ReplaceChild method. The ReplaceChild method takes two parameters, much like the InsertBefore and InsertAfter methods, but instead of using the existing node as a reference point, the existing node is removed from the node tree, and the new node is inserted in its place. The method returns the node that has been replaced . Listing 11.25 demonstrates how to use the ReplaceChild method. Listing 11.25C# XmlDocument doc = new XmlDocument(); doc.LoadXml("<root att1=\"first\" att4=\"last\"/>"); XmlElement newRoot = doc.CreateElement("NewRoot"); doc.ReplaceChild(newRoot, doc.DocumentElement); doc.Save("blah.xml"); VB Dim doc As new XmlDocument() doc.LoadXml("<root att1="&Chr(34)&"first"&Chr(34)& _ "att4="&Chr(34)&"last"&Chr(34)& "/>") Dim newRoot As doc.CreateElement("NewRoot") doc.ReplaceChild(newRoot, doc.DocumentElement) doc.Save("blah.xml") The ReplaceChild method may throw two exceptions. It may throw an ArgumentException if the new node was created from a different document or if the existing node is not a child of the container node. Also, the InvalidOperationException may be raised if the new node is not a valid child of the container node or if the new node is an ancestor of the container node. This would create a cycle in the node tree, which is not allowed.
|