Removing XmlNode s for an XmlDocument


Removing XmlNode s for an XmlDocument

In addition to inserting and replacing nodes, you may need to remove a node from the tree altogether. You can easily remove a node from the node tree by using the RemoveChild method on the XmlNode class.

The RemoveChild method takes one parameter: the node to remove. If this node is successfully removed, then it returns a reference to the removed node. If the node is not a child of the container node, then an ArgumentException is raised. Listing 11.26 shows how to use the RemoveChild method.

Listing 11.26
 C# XmlDocument doc = new XmlDocument(); doc.LoadXml("<root><child/></root>"); doc.DocumentElement.RemoveChild(doc.DocumentElement.FirstChild); doc.Save("out.xml"); VB Dim doc As New XmlDocument() doc.LoadXml("<root><child/></root>") doc.DocumentElement.RemoveChild(doc.DocumentElement.FirstChild) doc.Save("out.xml") 

The XmlNode class also provides the RemoveAll method, which removes all of the child nodes and any existing attributes from the container node. Listing 11.27 shows how to use the RemoveAll method.

Listing 11.27
 C# XmlDocument doc = new XmlDocument(); doc.LoadXml ("<root att=\"val\" ><child/><child att=\"val\"/></root>"); doc.DocumentElement.RemoveAll(); doc.Save("out.xml"); VB Dim doc As New XmlDocument() doc.LoadXml ("<root att="&Chr(34)&"val"&Chr(34)&"><child/>" & _ "<child att="&CHr(34)&"val"&Char(34)& "/></root>"); doc.DocumentElement.RemoveAll() doc.Save("out.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