10

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.

Leany
  • 159
  • 1
  • 2
  • 5
  • 2
    possible duplicate of [XML Data management in .NET](http://stackoverflow.com/questions/5974152/xml-data-management-in-net) – Daniel Hilgarth May 12 '11 at 08:16
  • 2
    You already asked that question. Please consult the documentation provided in the answers to your last question. – Daniel Hilgarth May 12 '11 at 08:16
  • possible duplicate of [How to add an existing Xml string into a XElement](http://stackoverflow.com/questions/1414561/how-to-add-an-existing-xml-string-into-a-xelement) – Sani Huttunen May 12 '11 at 08:16
  • Possible duplicate of [XML Data management in .NET](https://stackoverflow.com/questions/5974152/xml-data-management-in-net) – Liam May 22 '18 at 12:57

1 Answers1

29
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

Ahmad Kayyali
  • 8,233
  • 13
  • 49
  • 83