Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding XML in C#

Tags:

c#

encoding

I have a xml file which has umlauts in it like so:

<NameGe>ËÇ</NameGe>

Is there a way to read this file and write it out like so:

<NameGe>&#214;&#231;</NameGe>

so basically it should write the numeric/encoded value of the umlaut.

Regards.

like image 319
Codehelp Avatar asked Feb 22 '26 12:02

Codehelp


1 Answers

You can do it by overriding WriteString of XmlTextWriter

MemoryStream m = new MemoryStream();
MyWriter xmlWriter = new MyWriter(m);

XDocument xDoc = XDocument.Parse(xml);
xDoc.Save(xmlWriter);
xmlWriter.Flush();

string s = Encoding.UTF8.GetString(m.ToArray());

-

public class MyWriter : XmlTextWriter
{
    public MyWriter(Stream s) : base(s,Encoding.UTF8)
    {
    }
    public override void WriteString(string text)
    {
        base.WriteRaw(HttpUtility.HtmlEncode(text));
    }
}
like image 156
L.B Avatar answered Feb 25 '26 01:02

L.B