How to insert a new element in XML file?

  • Thread starter Thread starter Roshan
  • Start date Start date
R

Roshan

Hi all,

Let say I have the following XML file:


<?xml version="1.0" ?>
<Store>

<cdCollect>
<cd id="1">
<title>Latest Hits</title>
<price>17.3</price>
</cd>
</cdCollect>

<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>

</Store>


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

1. 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.

Regards,

Samir
 
I am using "XmlNodeWriter", you can find it in gotdotnet.com

Here is how I use that.
XmlNodeWriter wALI = new XmlNodeWriter(docXml, false);

YourObject.Serialize(wALI, dtAliAddress);



J.W.
 
XmlDocument doc = /* Load XML data. */ LoadDocument();
XmlNode parentNode = doc.DocumentElement; // Point at parent node of <book>.
XmlNode bookNode = doc.CreateNode(XmlNodeType.Element, "book", null);
doc.AppendChild(bookNode );
XmlAttribute attr = doc.CreateAttribute("id");
attr.InnerText = "4";
bookNode.Attributes.Append(attr);
XmlNode childNode = doc.CreateNode(XmlNodeType.Element, "title", null);
childNode.InnerText = "XML Bible";
bookNode.AppendChild(childNode);
// And further on..
 
Back
Top