Monday, 26 August 2013

How to replace text in XML document with special chars

How to replace text in XML document with special chars

With this method I want to open a document, replace some text and then
leave it alone. It works, thats something to be proud of. :D
public static void replaceInOpenXMLDocument(string pfad, string
zuErsetzen, string neuerString)
{
using (WordprocessingDocument doc =
WordprocessingDocument.Open(pfad, true))
{
var res = from bm in
doc.MainDocumentPart.Document.Body.Descendants()
where bm.InnerText != string.Empty &&
bm.InnerText.Contains(zuErsetzen) &&
bm.HasChildren == false
select bm;
foreach (var item in res)
{
item.InsertAfterSelf(new
Text(item.InnerText.Replace(zuErsetzen,
neuerString)));
item.Remove();
}
doc.Close();
}
}
But it only works on replacing without special characters. For example:
OS will be replaced with Windows over 9000 *[OS]* will be left as it is.
CASE 1:
In the document:
You use os for whatever purpose you've got.
replaceInOpenXMLDocument("C:\NSA\suspects.docx", "os", "Win 2000");
Will result in this:
You use Win 2000 for whatever purpose you've got.
CASE 2:
With special chars ...
You use [os] for whatever purpose you've got.
replaceInOpenXMLDocument("C:\NSA\suspects.docx", "[os]", "Win 2000");
... it just ignores me:
You use [os] for whatever purpose you've got.
I tried several special characters ()[]{} etc., but they're never replaced.
Is there something I forgot to do? Or is it simply not able to replace
with special characters with this method? If so, I just need a simple
workaround.
Is there anybody out to help with my desperation? :)

No comments:

Post a Comment