Remove Encoding Attribute from XmlDeclaration in C# when Serializing an Object.

Okay first I’m going to say that when got this request from a junior dev I thought they were asking how to remove the whole declaration. It seemed wrong to remove the encoding since that info can be important to some systems. Then they said the magic sentence…”need to support legacy app that is not expecting it” ah okay now it makes sense why you wouldn’t want it there.

This was what they were trying to serialize the object into.

<?xml version="1.0" ?>
<parserspec>
	<field name="Test1" start="0" end="5"/>
	<field name="Test2" start="6" end="10"/>
	<field name="Test3" start="11" end="20"/>
	<field name="Test4" start="21" end="25"/>
</parserspec>

As you can see there is no encoding attribute in the xml declaration. The question now is how do you remove the encoding attribute.

My first thought was that there has to be a setting in XmlWritterSettings class that can do that…but after about an hour of googling and testing I couldn’t get the encoding attribute removed. I could remove the whole xml declaration but not just the encoding attribute.

Strange that there was not a setting or at least not one I could find, but then I stumbled across the WriteRaw() method in the XmlWriter class. Hmm if I can’t remove it can I just write a custom one myself.

So I gave it a shot and it worked…

Below is the object that will be serialized and the code to do it.

[XmlRoot(ElementName = "parserspec")]
public class ParserSpec
{
    [XmlElement(ElementName = "field")]
    public List<FixedWidthField> Fields { get; set; }
    public ParserSpec()
    {
        Fields = new List<FixedWidthField>();
    }
}
//Code to serialize into xml.
public static string SerializesToXmlWithCustomXmlDeclaration<T>(T obj)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    //make sure you omit the default declaration since you will be writing your own.
    XmlWriterSettings settings = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };
    //get rid of the xml namespaces.
    XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
    nameSpace.Add("", "");
    StringBuilder sb = new StringBuilder();
    using (XmlWriter writer = XmlWriter.Create(sb, settings))
    {
        //write the custom declaration
        string xmlDec = @"<?xml version=""1.0""?>" + Environment.NewLine;
        char[] xmlDecChars = xmlDec.ToArray();
        writer.WriteRaw(xmlDecChars, 0, xmlDecChars.Length);
        //then serialize the rest of the object
        xmlSerializer.Serialize(writer, obj, nameSpace);
    }
    return sb.ToString();
}

This results in the following..

Cheers!