'Writing Escape Characters in Plain Text with XML

I'm having an issue parsing some XML with C#. To give an example, I'm taking some XML that contains the following tag:

<Message>Hello, my name is&#xA;Mr. Rogers</Message>

And parsing it with the following C# code:

var xmlData = XDocument.Load(filePath);

The problem that I'm having is that the above XML is being parsed as:

<Message>Hello, my name is
Mr. Rogers</Message>

when it needs to be parsed as:

<Message>Hello, my name is&#xA;Mr. Rogers</Message>

Is it possible to just have it parsed as the latter example in C#?



Solution 1:[1]

The only way is to do pre- and post-processing.

public XDocument LoadXDocument(string xmlString)
{
    const string replacer = "|||==|||";
    const string replacement = "&#xA;";
    xmlString = xmlString.Replace(replacement, replacer);

    XDocument doc;
    using (var reader = new StringReader(xmlString))
    {
        doc = XDocument.Load(reader);
    }

    foreach (var element in doc.Elements())
    {
        if (element.Value.Contains(replacer))
        {
            element.SetValue(element.Value.Replace(replacer, replacement));
        }
    }

    return doc;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pavel Koryakin