Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new node to existing XmlDocument object

Tags:

c#

xml

I have an xml of following format.

<BOOKS>
    <BOOK>
        <TITLE>book 1</TITLE>
        <AUTHOR>author 1</AUTHOR>       
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </BOOK>
    <BOOK>
        <TITLE>book 2</TITLE>
        <AUTHOR>author 2</AUTHOR>       
        <PRICE>20.90</PRICE>
        <YEAR>1995</YEAR>
    </BOOK>
</BOOKS>

I have an Add(XmlDocument xDoc, Book newBook) method to add new book to the XmlDocument object that is passed to the Add(..) method. How can I do this.

like image 478
Leany Avatar asked May 12 '11 08:05

Leany


1 Answers

XmlDocument doc = new XmlDocument();
doc.Load("file.xml");
XmlElement foo = doc.CreateElement("foo");
XmlElement bar = doc.CreateElement("bar");
bar.InnerText = "whatever";
foo.AppendChild(bar);
doc.DocumentElement.AppendChild(foo);
doc.Save("file.xml");

see Martin Honnen Post at: Adding a new Node to existing XML document

like image 62
Ahmad Kayyali Avatar answered Sep 23 '22 22:09

Ahmad Kayyali