如何在使用字节和MemoryStream时忽略WordML document.xml中的xml声明?
问题描述:
我的代码片段2其中不同的工作如何在使用字节和MemoryStream时忽略WordML document.xml中的xml声明?
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 =新XmlWriterSettings { OmitXmlDeclaration =真 }; 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并且不存在此问题。
答
这是错误的:
byte[] wordDocBytes = streamWithWord.GetBuffer();
这应该是:
byte[] wordDocBytes = streamWithWord.ToArray();
GetBuffer
返回缓冲区的额外部分 - 不仅是有效数据。
您通常可以省略带有XmlWriterSettings
的xml标题。
几乎可以肯定地直接写,但我即将用完信号(在火车上...)。