csharp employee
csharp employee

Reputation: 3

System.ArgumentException: Cannot Write XML Declaration. WriteStartDocument method has already written it

Hi I am trying to process multiple XML files by merging it with strings from an excel file. This is how it is written in my code

try
{
    CXMLProcessing xmlProc = new CXMLProcessing();
    Demo = Demo + 1;
    string OutputData = "";
    string attr = "";
    XmlDocument doc = new XmlDocument();
    doc.Load(fileItem);
    XmlNode node = doc.DocumentElement;
    xmlProc.CreateXML(node, ref OutputData, ref attr, dictionary, textBoxCNFLCID.Text, radioReference.Checked);
    XmlTextWriter xmlwriter = new XmlTextWriter(textOutputCNF.Text + file_Name, fileEncoding);
    xmlwriter.Formatting = Formatting.Indented;
    xmlwriter.WriteStartDocument(true);
    doc.Save(xmlwriter);
    //xmlwriter = null;
    doc = null;
    xmlProc=null;
    xmlwriter.WriteEndDocument();
    return true;
}

It seems that I cannot proceed into saving the file into xml because of WriteStartDocument accessing it. This happens everytime I try to work on multiple files. Is there a way I can bypass this exception? I tried adding a .Close but it still gets the exception. This is written in C#. Thanks.

Upvotes: 0

Views: 2335

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500495

Well yes - calling doc.Save will try to start a document again.

Have you considered calling:

doc.DocumentElement.WriteTo(xmlwriter);
writer.WriteEndDocument();

?

Or just remove the call to xmlwriter.WriteStartDocument... it's not at all clear why you're doing that in the first place.

(You should also use a using statement for xmlwriter, and remove the pointless assignments to null at the end of the method.)

Upvotes: 1

Related Questions