我的代碼片段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並且不存在此問題。