J'ai 2 extraits de code qui fonctionnent différemmentComment omettre la déclaration XML dans WordML document.xml lorsque vous travaillez avec bytes et MemoryStream?
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());
}
Ici, il fonctionne très bien et génère bien .docx.
Maintenant deuxième façon de le faire avec octets et 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);
Lorsque vous effectuez la 2ème méthode, le document généré n'est pas bon. Dans son document.xml, vous verrez une déclaration XML. Le fichier initialXml représente XElement du fichier XML WordML initial.
<?xml version="1.0" encoding="utf-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
....
Et quand vous essayez de l'ouvrir dans Word il vous donne le message que le fichier est tronqué.
Comment puis-je utiliser les octets et MemoryStreams et ne pas avoir ce problème.