在保存损坏的文件的XML文档的结果 [英] Saving an xml document results in corrupt file

查看:189
本文介绍了在保存损坏的文件的XML文档的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何将xmlDoc中保存为Word文件的问题。我想打开word文件,请使用XmlDocument类的则由底层XML结构的一些操作,然后重新保存回字的文件。这是林目前做的:

I have a question on how to save an xmldoc as a word file. I want to open the word file, do some manipulation on the undelying xml structure using the xmldocument class and then resave it back to the word file. This is what im currently doing:

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"E:\HelloWorld.docx", true))
                {
                   MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                   var xmlDoc = new XmlDocument();
                   using (Stream partStream = part.GetStream())
                   using (XmlReader partXmlReader = XmlReader.Create(partStream))
                     xmlDoc.Load(partXmlReader);
                   //xml node manipulation here

                   xmlDoc.Save(@"E:\HelloWorld.docx");
                 }

这将导致损坏的文档中不过。什么是做这个功能的正确方法?

This results in a corrupt document however. What is the proper way to do this functionality?

推荐答案

OpenXML文档不仅仅是一个XML文件(实际上,这是一个ZIP更多包含其中的几个文件,XML文件归档)。

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

你应该做的是修改 WordprocessingDocument ,然后保存(这是在使用块结束时自动完成),不保存表示文档的一部分XML文件:

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);
    }
}

这篇关于在保存损坏的文件的XML文档的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆