问题
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?
回答1:
OpenXML document is more than just a XML file (actually, it's a ZIP archive containing several files, XML files among them).
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);
}
}
回答2:
If you have successfully performed the manipulation you can later save back to file using Close() on your wordDoc
variable. The MSDN states that this also saves the content.
回答3:
docx will be an XML file, not DOCX.
var xmlDoc = new XmlDocument();
...
xmlDoc.Save(@"E:\HelloWorld.docx");
What you want is either create new WordprocessingDocument or update existing one with the XML you've modified. Something along the lines
using (StreamWriter sw =
new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
xmlDoc.Save(sw);
}
See more samples in the MSDN: http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.document.aspx
来源:https://stackoverflow.com/questions/9842376/saving-an-xml-document-results-in-corrupt-file