开发者

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, textBoxCNFLCI开发者_运维技巧D.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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜