Working with the InsertBefore and InsertAfter MethodsIf 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.22C# 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. |