<?xml version="1.0" encoding="utf-16"?>
More often than not you want UTF-8; .NET XElement won't even read the UTF-16 contents back in using the Load() method (and things like IE won't be able to view it in the browser). To work around this problem I derive a new StringWriter and override the Encoding method:
public class StringWriterWithEncoding : StringWriter
{
private Encoding mEncoding;
public StringWriterWithEncoding(Encoding encoding)
{
mEncoding = encoding;
}
public override Encoding Encoding
{
get { return mEncoding; }
}
}
Now just use the new class and the XElement.Save() method to write as UTF-8:
XElement xml = XElement.Parse("<root/>");
using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
{
xml.Save(writer);
Console.WriteLine(writer.ToString());
}
No comments:
Post a Comment