Hisham Maudarbocus Hisham Maudarbocus - 1 year ago 76
C# Question

Creating and using custom XML special characters with XmlSerializer

I have a

class that stores basic information about a color format. The aim is to be able to serialize and deserialize to and from XML. To represent Red, Green and Blue I use special color string identifiers:

public const string RedColorIdentifier = "&red;";
public const string GreenColorIdentifier = "&green;";
public const string BlueColorIdentifier = "&blue;";

For a format like "#RGB", the class format string is as such:

colorFormat.Format = "#" + ColorFormat.RedColorIdentifier +
ColorFormat.GreenColorIdentifier +

Ideally, the serialized XML should be:

<ColorFormat Name="HexFmt" ColorBase="Hex">#&red;&green;&blue;</ColorFormat>

The actual serialization is:

<ColorFormat Name="HexFmt" ColorBase="Hex">#&amp;red;&amp;green;&amp;blue;</ColorFormat>

I was wondering if:

  1. There is a way of "serializing and deserializing" your own custom special XML character

  2. The new XML structure will eventually caused problem, such as well formedness etc...

Answer Source

Finally found it, gotta implement IXmlSerializable as such:

public class ColorFormat : IXmlSerializable

    public XmlSchema GetSchema()
        return null;

    public void ReadXml(XmlReader reader)
        Name = reader.GetAttribute(nameof(Name));
        ColorBase = CommonUtil.ParseStringToEnum<NumberBase>(reader.GetAttribute(nameof(ColorBase)));
        Format = reader.ReadInnerXml();

    public void WriteXml(XmlWriter writer)
        writer.WriteAttributeString(nameof(Name), Name);
        writer.WriteAttributeString(nameof(ColorBase), ColorBase.ToString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download