Saving an xml document results in corrupt file

坚强是说给别人听的谎言 提交于 2019-12-06 13:35:27

OpenXML document is more than just a XML file (actually, it's a ZIP archive containing several files, XML files among them).

What you should do is to modify your WordprocessingDocument and then save it (which is done automatically at the end of the using block), not save the XML file that represents part of the document:

using (var wordDoc = WordprocessingDocument.Open(fileName, true))
{
    MainDocumentPart mainPart = wordDoc.MainDocumentPart;

    using (Stream partStream = mainPart.GetStream())
    {
        var xmlDoc = new XmlDocument();

        using (XmlReader partXmlReader = XmlReader.Create(partStream))
            xmlDoc.Load(partXmlReader);

        //xml node manipulation here

        partStream.Position = 0;

        using (XmlWriter partXmlWriter = XmlWriter.Create(partStream))
            xmlDoc.Save(partXmlWriter);
    }
}

If you have successfully performed the manipulation you can later save back to file using Close() on your wordDoc variable. The MSDN states that this also saves the content.

docx will be an XML file, not DOCX.

var xmlDoc = new XmlDocument();
... 
xmlDoc.Save(@"E:\HelloWorld.docx");

What you want is either create new WordprocessingDocument or update existing one with the XML you've modified. Something along the lines

using (StreamWriter sw =
    new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        xmlDoc.Save(sw);
    }

See more samples in the MSDN: http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.document.aspx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!