Working with the InsertBefore and InsertAfter Methods


Working with the InsertBefore and InsertAfter Methods

If you need to insert a node in the middle of a container node's child list, you cannot use AppendChild or PrependChild . Instead, you must use InsertBefore and InsertAfter . Both methods take two XmlNode objects as parameters. The first XmlNode object is the XmlNode to be inserted. The second XmlNode object is the reference node. When using InsertBefore , the new node will be inserted before the reference node, and it will be inserted after the reference node when calling InsertAfter . Listing 11.22 creates two elements and adds one before the reference node and one after the reference node.

Listing 11.22
 C# XmlDocument doc = new XmlDocument(); doc.LoadXml("<root><first/><last/></root>"); XmlNode first = doc.DocumentElement.FirstChild; XmlNode last = doc.DocumentElement.LastChild; XmlElement secondChild = doc.CreateElement("", "second", ""); XmlElement thirdChild = doc.CreateElement("", "third", ""); doc.DocumentElement.InsertAfter(secondChild, first); doc.DocumentElement.InsertBefore(thirdChild, last); doc.Save("blah.xml"); VB Dim doc As New XmlDocument() doc.LoadXml("<root><first/><last/></root>") Dim first As doc.DocumentElement.FirstChild Dim last As doc.DocumentElement.LastChild Dim secondChild As XmlElement secondChild =  doc.CreateElement("", "second", "") Dim thirdChild As XmlElement thirdChild = doc.CreateElement("", "third", "") doc.DocumentElement.InsertAfter(secondChild, first) doc.DocumentElement.InsertBefore(thirdChild, last) doc.Save("blah.xml") 

Just like AppendChild and PrependChild , the InsertBefore and InsertAfter methods return the XmlNode that is added to the document tree. Also, there are two exceptions to beware of when using this method. Like with any insertion method, an InvalidException will be thrown if the specified node is not a valid child. An ArgumentException will be raised if the reference node is not a child of the current node or if the new child is created from a different document. Again, you can use ImportNode to import the node into the current document.



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