Manipulating a Word 2007 XML Document in C #

I am trying to manipulate the XML of a Word 2007 document in C #. I managed to find and process the node I want, but now I can’t figure out how to save it. Here is what I am trying:

// Open the document from memoryStream Package pkgFile = Package.Open(memoryStream, FileMode.Open, FileAccess.ReadWrite); PackageRelationshipCollection pkgrcOfficeDocument = pkgFile.GetRelationshipsByType(strRelRoot); foreach (PackageRelationship pkgr in pkgrcOfficeDocument) { if (pkgr.SourceUri.OriginalString == "/") { Uri uriData = new Uri("/word/document.xml", UriKind.Relative); PackagePart pkgprtData = pkgFile.GetPart(uriData); XmlDocument doc = new XmlDocument(); doc.Load(pkgprtData.GetStream()); NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", nsUri); XmlNodeList nodes = doc.SelectNodes("//w:body/w:p/w:r/w:t", nsManager); foreach (XmlNode node in nodes) { if (node.InnerText == "{{TextToChange}}") { node.InnerText = "success"; } } if (pkgFile.PartExists(uriData)) { // Delete template "/customXML/item1.xml" part pkgFile.DeletePart(uriData); } PackagePart newPkgprtData = pkgFile.CreatePart(uriData, "application/xml"); StreamWriter partWrtr = new StreamWriter(newPkgprtData.GetStream(FileMode.Create, FileAccess.Write)); doc.Save(partWrtr); partWrtr.Close(); } } pkgFile.Close(); 

I get the error "The memory stream is not expanding." Any ideas?

+4
source share
5 answers

I would recommend you use the Open XML SDK instead of hacking the format yourself.

+8
source

Using the OpenXML SDK 2.0, I do this:

 public void SearchAndReplace(Dictionary<string, string> tokens) { using (WordprocessingDocument doc = WordprocessingDocument.Open(_filename, true)) ProcessDocument(doc, tokens); } private string GetPartAsString(OpenXmlPart part) { string text = String.Empty; using (StreamReader sr = new StreamReader(part.GetStream())) { text = sr.ReadToEnd(); } return text; } private void SavePart(OpenXmlPart part, string text) { using (StreamWriter sw = new StreamWriter(part.GetStream(FileMode.Create))) { sw.Write(text); } } private void ProcessDocument(WordprocessingDocument doc, Dictionary<string, string> tokenDict) { ProcessPart(doc.MainDocumentPart, tokenDict); foreach (var part in doc.MainDocumentPart.HeaderParts) { ProcessPart(part, tokenDict); } foreach (var part in doc.MainDocumentPart.FooterParts) { ProcessPart(part, tokenDict); } } private void ProcessPart(OpenXmlPart part, Dictionary<string, string> tokenDict) { string docText = GetPartAsString(part); foreach (var keyval in tokenDict) { Regex expr = new Regex(_starttag + keyval.Key + _endtag); docText = expr.Replace(docText, keyval.Value); } SavePart(part, docText); } 

From this, you can write GetPartAsXmlDocument, do what you want with it, and then pass it back using SavePart (part, xmlString).

Hope this helps!

+2
source

The problem is that the problem is doc.Save (partWrtr), which is created using newPkgprtData, which is created using pkgFile, which is loaded from the memory stream ... Since you are loaded from the memory stream, it tries to save the document back to that same memory stream. This results in the error you see.

Instead of saving to a memory stream, try saving it in a new file or in a new memory stream.

+1
source

Short and simple answer to the question with "Memory stream is not expanding": Do not open the document from MemoryStream. Therefore, in this regard, the earlier answer is correct, just open the file.

Opening a document from MemoryStream to edit a document (in my experience) will easily result in a "memory stream not expanding." I believe that the message appears when edited, which requires an expansion of the memory stream. I found that I can make some changes, but not everything that adds size. Thus, f.ex deletes the user part of xml in order, but adding one and some data is not.

So, if you really need to open a memory stream, you have to figure out how to open an expandable MemoryStream if you want to add to it. I need this and hope to find a solution.

Stein-Tore Erdal

PS: just noticed the answer from "January 26, 2011 at 15:18". Do not think that this is the answer in all situations. I get an error when trying:

  var ms = new MemoryStream(bytes); using (WordprocessingDocument wd = WordprocessingDocument.Open(ms, true)) { ... using (MemoryStream msData = new MemoryStream()) { xdoc.Save(msData); msData.Position = 0; ourCxp.FeedData(msData); // Memory stream is not expandable. 
0
source

Source: https://habr.com/ru/post/1336967/


All Articles