Insert node

  • Thread starter Thread starter davidfahy
  • Start date Start date
D

davidfahy

Hi all,

Let say I have the following XML file:

<Books>
<book id = "1">
<title>ASP.NET</title>
<isbn>121212</isbn>
<price>32.65</price>
</book>
<book id = "2">
<title>Visual C#</title>
<isbn>4433434</isbn>
<price>56.32</price>
</book>
<book id = "3">
<title>ADO.NET</title>
<isbn>43434</isbn>
<price>55.65<.price>
</book>
</Books>


Now, how can I do the following by using C#:

How to insert a new element with child nodes as shown below under
<Books>...</Books>? :
<book id = "4">
<title>XML Bible</title>
<isbn>77676</isbn>
<price>85.65</price>
</book>


Thank you,

Your help is very very much appreciated.
 
Depends on the quantity; if the xml is not immense, the XmlDocument will do
the job:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlElement root = doc.DocumentElement, newBook =
doc.CreateElement("book");
newBook.SetAttribute("id", "4");
newBook.AppendChild(doc.CreateElement("title")).InnerText = "XML
Bible";
newBook.AppendChild(doc.CreateElement("isbn")).InnerText = "77676";
newBook.AppendChild(doc.CreateElement("price")).InnerText = "85.65";
root.InsertAfter(newBook, root.LastChild);
Debug.WriteLine(doc.OuterXml);

Marc
 
Here an example based on your xml:

XmlDocument xmlBook = new XmlDocument();

xmlBook.Load(@"books.xml");

XmlDocument xmlBookToInsert = new XmlDocument();

xmlBookToInsert.Load(@"books_to_insert.xml");

XmlNode nodeToImport = xmlBookToInsert.SelectSingleNode("/book");

XmlNode node = xmlBook.ImportNode(nodeToImport, true);

xmlBook.DocumentElement.AppendChild(node);
 
Back
Top