Replacing the XmlNode s within an XmlDocument


Replacing the XmlNode s within an XmlDocument

Using 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.25
 C# 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.

ATTRIBUTE REPLACEMENT USING THE INSERTION METHODS

To replace an attribute node by using the XmlAttributeCollection , you can simply use the insertion methods, passing an attribute with the same name as the attribute you would like to replace. The insertion method will remove the existing attribute and add the new attribute. The following code demonstrates removing an attribute through the Append method:

 
 C# XmlDocument doc = new XmlDocument(); doc.LoadXml("<root att1=\"first\" att4=\"last\"/>"); XmlAttribute newFirst = doc.CreateAttribute("att1"); newFirst.Value = "1st"; XmlAttributeCollection atts = doc.DocumentElement.Attributes; atts.Append(newFirst); doc.Save("blah.xml"); VB Dim doc As New XmlDocument() 0doc.LoadXml("<root att1="&Chr(34)&"first"&Chr(34)& _             "att4="&Chr(34)&"last"&Chr(34)& "/>") Dim newFirst As doc.CreateAttribute("att1") newFirst.Value = "1st" Dim atts As doc.DocumentElement.Attributes atts.Append(newFirst) doc.Save("blah.xml") 



Microsoft.NET Compact Framework Kick Start
Microsoft .NET Compact Framework Kick Start
ISBN: 0672325705
EAN: 2147483647
Year: 2003
Pages: 206

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net