For this XmlElement I need to be able to set the inner text to an escaped version of the Unicode string, even though the document is ultimately encoded in UTF-8. Is there any way to achieve this?
Here is a simple version of the code:
const string text = "ñ"; var document = new XmlDocument {PreserveWhitespace = true}; var root = document.CreateElement("root"); root.InnerXml = text; document.AppendChild(root); var settings = new XmlWriterSettings {Encoding = Encoding.UTF8, OmitXmlDeclaration = true}; using (var stream = new FileStream("out.xml", FileMode.Create)) using (var writer = XmlWriter.Create(stream, settings)) document.WriteTo(writer);
Expected:
<root>ñ</root>
Actual:
<root>ñ</root>
Using the XmlWriter direct and calling WriteRaw(text) works, but I only have access to the XmlDocument , and serialization will happen later. On an XmlElement , InnerText stands out & before & as expected, and setting Value throws an exception.
Is there a way to set the inner XmlElement text to escaped ASCII text, regardless of the encoding used? I feel like I should be missing out on something obvious, or it's just not possible.
source share