For those of you who Serialize XML a lot you may have noticed that the default XML Encoding is UTF-16. This is great if you are working with other .NET applications, but if you need to interoperate with applications that do not support UTF-16 you will need a means of creating XML documents that are UTF-8 or some other Encoding type. The easiest way to accomplish this is to create a custom StringWriter class.
using System;
using System.IO;
using System.Text;
/// <summary>
/// Used to pass into
/// <code>XmlTextWriter.Create()</code>
/// Constructors to ensure
/// the resulting XML encoding is
/// set to UTF-8 vice the default
/// UTF-16
/// </summary>
/// <remarks>
/// This is required when writing XML
/// that is targeted for Web Methods
/// which cannot support UTF-16
/// </remarks>
public sealed class Utf8XmlStringWriter
: StringWriter
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="formatProvider">
/// Format information to use when
/// writing strings</param>
/// <remarks>
/// If no specific format requirements
/// exist, use InvarientCulture
/// </remarks>
public Utf8XmlStringWriter(IFormatProvider formatProvider)
: base(formatProvider)
{ }
/// <summary>
/// This override property ensure
/// that the consuming XMLWriter
/// class defaults to UTF-8
/// encoding
/// </summary>
public override Encoding Encoding
{
get
{
return Encoding.UTF8;
}
}
}
Once created, you can use as part of your serialization routines and the resulting document will be encoded as requested.
/// <summary>
/// XML Serializes object and returns
/// its XML form as a string.
/// </summary>
/// <param name="source">The object
/// to be serialized</param>
/// <param name="formatting">Formatting
/// to be applied to the XML being
/// produced</param>
/// <param name="writeUtf16">Flag to
/// indicate whether or not the XML
/// written is UTF-8 (false) or UTF-16
/// (true)</param>
/// <returns>Strongly type version of
/// the xml fragment</returns>
/// <remarks>Objects submitted for
/// serialization must be decorated
/// with the <code>Serializable</code>
/// attribute.</remarks>
public static string XmlSerialize(object source, Formatting formatting, bool writeUtf16)
{
XmlSerializer serializer = new XmlSerializer(source.GetType());
StringWriter stringWriter;
if (writeUtf16)
stringWriter = new StringWriter(Thread.CurrentThread.CurrentCulture);
else
stringWriter = new Utf8XmlStringWriter(Thread.CurrentThread.CurrentCulture);
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = formatting;
serializer.Serialize(xmlWriter, source);
xmlWriter.Close();
return stringWriter.ToString();
}
Tags: xml, design patterns