在使用bytes和MemoryStream时,如何在WordML document.xml中省略xml声明?

时间:2010-05-12 13:27:22

标签: c# openxml-sdk wordml

我有两段不同的代码片段

using (WordprocessingDocument wordDocument =
           WordprocessingDocument.Create(@"D:\Tests\WordML\ML_Example.docx", WordprocessingDocumentType.Document))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
            TextReader tr = new StreamReader("SimpleTextExample.xml");
            mainPart.Document = new Document(tr.ReadToEnd());
        }

这里效果很好并且生成.docx好。

现在用字节和MemoryStream-uri制作它的第二种方法。

 MemoryStream modeleRootStream = new MemoryStream();

XmlWriterSettings writerSettings = new XmlWriterSettings                                                    {                                                        OmitXmlDeclaration = true                                                    }; XmlWriter xmlWriter = XmlWriter.Create(modeleRootStream,writerSettings);

        initialXml.WriteTo(xmlWriter);

        xmlWriter.Flush();

        modeleRootStream.Position = 0;
       MemoryStream streamWithWord = new MemoryStream();

        using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(streamWithWord,
            WordprocessingDocumentType.Document))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

            string streamContent = string.Empty;

            using (StreamReader reader = new StreamReader(modeleRootStream))
            {
               streamContent = reader.ReadToEnd();
            }

            mainPart.Document = new Document(streamContent);
        }

        byte[] wordDocBytes = streamWithWord.GetBuffer();

        streamWithWord.Close();

        File.WriteAllBytes(@"D:\Tests\WordML\ML_Example1.docx", wordDocBytes);

当你以第二种方式生成时,生成的文档不好。在它的document.xml中你会看到xml声明。 initialXml表示初始WordML xml的XElement。

<?xml version="1.0" encoding="utf-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">

   ....

当您尝试在Word中打开它时,它会向您显示文件被截断的消息。

如何使用字节和MemoryStreams而不会出现此问题。

1 个答案:

答案 0 :(得分:1)

这是错误的:

byte[] wordDocBytes = streamWithWord.GetBuffer();

应该是:

byte[] wordDocBytes = streamWithWord.ToArray();

GetBuffer返回缓冲区的 extra 部分 - 而不仅仅是有效数据。

您通常可以使用XmlWriterSettings省略xml标题。

几乎可以肯定的是,写作更直接,但我即将耗尽信号(在火车上......)。