Using the AppendChild and PrependChild Methods


Using the AppendChild and PrependChild Methods

The two most commonly used node-insertion methods are the AppendChild method, which appends the specified node as the last child of the current node, and PrependChild , which prepends the specified node as the first child of the current node. Listing 11.21 creates two elements, adds one to the beginning of the root node's list, and adds another to the end of the root node's list.

Listing 11.21
 C# XmlDocument doc = new XmlDocument(); doc.LoadXml("<root/>"); XmlElement firstChild = doc.CreateElement("", "First", ""); XmlElement lastChild = doc.CreateElement("", "Last", ""); doc.DocumentElement.PrependChild(firstChild); doc.DocumentElement.AppendChild(lastChild); doc.Save("out.xml"); VB Dim doc As new XmlDocument() doc.LoadXml("<root/>") Dim firstChild As XmlElement firstChild = doc.CreateElement("", "First", "") Dim lastChild As XmlElement lastChild = doc.CreateElement("", "Last", "") doc.DocumentElement.PrependChild(firstChild) doc.DocumentElement.AppendChild(lastChild) 1doc.Save("out.xml") 

These methods return the node that was added to the document tree. It is possible for two exceptions to be thrown when using these methods. As discussed before, an InvalidOperation will be thrown if the specified node cannot be inserted as a valid child, and an ArgumentException will be raised if the node is created from a document different from the one that created this node. In this case you can use the XmlDocument.ImportNode method to import the node into the current document. The ImportNode method returns an XmlNode that can then be inserted into the 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