This is happening because the Open XML word usually creates when a text contains special characters might look like :
<w:r w:rsidRPr="00316587">
<w:rPr>
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:eastAsia="Times New Roman" w:cs="Consolas" />
<w:color w:val="823125" />
<w:sz w:val="20" />
<w:szCs w:val="20" />
<w:lang w:eastAsia="en-GB" />
</w:rPr>
<w:t>[</w:t>
</w:r>
<w:proofErr w:type="gramStart" />
<w:r w:rsidRPr="00316587">
<w:rPr>
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:eastAsia="Times New Roman" w:cs="Consolas" />
<w:color w:val="823125" />
<w:sz w:val="20" />
<w:szCs w:val="20" />
<w:lang w:eastAsia="en-GB" />
</w:rPr>
<w:t>text-to-replace</w:t>
</w:r>
<w:proofErr w:type="gramEnd" />
<w:r w:rsidRPr="00316587">
<w:rPr>
<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:eastAsia="Times New Roman" w:cs="Consolas" />
<w:color w:val="823125" />
<w:sz w:val="20" />
<w:szCs w:val="20" />
<w:lang w:eastAsia="en-GB" />
</w:rPr>
<w:t>]</w:t>
</w:r>
</w:p>
The above shows open xml created for text [text-to-replace]
. (Please note this might not always be the case, may be depends on the client you are using).
By the looks of your code doc.MainDocumentPart.Document.Body.Descendants()
you are taking all the OpenXmlPart
type Descendants for the whole body of the document and trying to replace the text iterating over one-by-one which leaves the actual text to be in one part and the special characters in two sperate parts. Hence the code fails to acheieve the required.
There might be different ways to workaround this.
Solution:
A nice (my preferred) solution would be to normalize the xml using Markup Simplifier from OpenXml Powertools, which will normalize the open xml markup to concatenate the text in a paragraph to simplify working programatically.
Example code:
using (WordprocessingDocument doc =
WordprocessingDocument.Open("Test.docx", true))
{
SimplifyMarkupSettings settings = new SimplifyMarkupSettings
{
NormalizeXml = true, // Merges Run's in a paragraph with similar formatting
};
MarkupSimplifier.SimplifyMarkup(doc, settings);
}
Please Refer to my answer here for more info on using MarkupSimplifier
Hope this helps :)