December 28, 2016

Exception: This document already has a 'DocumentElement' node Exception in C#

While manipulating an XML file I came across with this exception and googled it out for solution. I found many stuffs but none of those were relevant and could not resolve my problem. After few minutes of analysis, I came to know that I was doing something wrong.


I was trying to add element directly to XML document, which was not correct. It should be added within the root element. I changed my code accordingly and it was resolved. Full XML file and C# code is given below. Hope this will be helpful for others, and please feel free to add comments or any queries.


XML file:











C# code:

XmlDocument doc = new XmlDocument();
            doc.Load("xml_file_path");

            // Create new element:
            XmlElement book = doc.CreateElement("Book");

            // Create child elements:
            XmlElement title = docDestn.CreateElement("Title");
            title.InnerText = "Mastering in ASP.Net 4.5";

            XmlElement author = docDestn.CreateElement("Author");
            title.InnerText = "Unknown Author";

            XmlElement version = docDestn.CreateElement("Version");
            title.InnerText = "V4.5";

            book.AppendChild(title);
            book.AppendChild(author);
            book.AppendChild(version);

            // Read the root node:
            XmlNode root = doc.SelectSingleNode("AllBooks");
            root.AppendChild(book);
            doc.Save("xml_file_path");

No comments:

Post a Comment