Akshay katale
Akshay katale

Reputation: 157

OpenXmlPowerTools.TextReplacer.SearchAndReplace is not working on word document

I'm working on a simple document merge. Wanted to find some strings and replace it with another string (Outside table).

So here is the issue, when i try to use TextReplacer.SearchAndReplace after accessing table using var table = wordDoc.MainDocumentPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Table>(); then SearchAndReplace is not working. Don't know what is the issue.

eg code:

 private static async Task MergeDoc(WordprocessingDocument wordDoc) {
    
    var table = wordDoc.MainDocumentPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Table>();
 
    TextReplacer.SearchAndReplace(wordDoc, "string to replace", "value", true);
 }

If I remove the table variable which actually a reference to the table from word document, then SearchAndReplace is working

Upvotes: 1

Views: 396

Answers (1)

Brian Heward
Brian Heward

Reputation: 556

You are getting a reference to an XML element. The SearchAndReplace function under the hood is trying to replace that element with a copied version, (not modify it.)

If you look at the similar function just above the one you are using, it uses GetModifiedWmlDocument() to re-grab the document because the old one is stale.

You can see what the function does here: https://github.com/OpenXmlDev/Open-Xml-PowerTools/blob/921cbccf6ecb29456eedc8d4d7834c7bf62c54c9/OpenXmlPowerTools/TextReplacer.cs#L209

Upvotes: 0

Related Questions