Siva CCSPL
Siva CCSPL

Reputation: 105

Recreate the same XML document if the original XML document is deleted

I developed a sample application to create an XML document, and I created and saved the XML documented. The application is still running but I delete that XML document and I am now trying to create a new XML using the same application. I got an error of

this document already has 'DocumentElement' node

if (File.Exists(AppPath) == false)
{
    root = doc.CreateElement("LicenseDetails");
    
    rootnode = doc.CreateElement("License");
    Login = doc.CreateElement("Login_Name");
    Login.InnerText = "KSC";
    rootnode.AppendChild(Login);
    root.AppendChild(rootnode);
    doc.AppendChild(root);
    doc.Save(AppPath);
}

I can easily append the node in existing XML document but what I want to do is: if my XML got deleted, application has to create a new XML with same tags.

Upvotes: 0

Views: 19593

Answers (2)

Ganesh R.
Ganesh R.

Reputation: 4385

The issue is even if you delete the XML, the doc element you are using is the same one as before. So when you try to add the root element to the doc element exception is thrown. A possible solution is as as follows:

eg:

 XmlDocument doc;
 XmlElement root;
 XmlElement rootnode;
 XmlElement Login;

 if (File.Exists(@"C:\Test.xml") == false)
 {
     doc = new XmlDocument();
     root = doc.CreateElement("LicenseDetails");

     rootnode = doc.CreateElement("License");
     Login = doc.CreateElement("Login_Name");
     Login.InnerText = "KSC";
     rootnode.AppendChild(Login);
     root.AppendChild(rootnode);
     doc.AppendChild(root);

     doc.Save(@"C:\Test.xml");
 }

So when you get to this block again it will execute without issues.

Upvotes: 3

KV Prajapati
KV Prajapati

Reputation: 94625

Use DocumentElement property - It return the root element of Xml document.

    XmlDocument dom=new XmlDocument();
    dom.Load("file.xml");
    XmlElement ele1=dom.createElement("A");
    XmlElement ele2=dom.createElement("B");
    ele1.AppendChild(ele2);
    dom.DocumentElement.AppendChild(ele1);
    dom.Save("file.xml");

Upvotes: 2

Related Questions