Most elegant XML serialization of Color structure

Viewed 26045

One problem bugged me enough to register on Stack Overflow. Currently if I want to serialize Color to XML string as named color, or #rrggbb, or #aarrggbb, I do it like this:

[XmlIgnore()]
public Color color;

[XmlElement(ElementName = "Color")]
public String color_XmlSurrogate
{
  get { return MyColorConverter.SetColor(color); }
  set { color = MyColorConverter.GetColor(value); }
}

Here MyColorConverter does serialization just the way I like it. But all this feels like a kludge, with additional field and all. Is there a way to make it work in less lines, maybe connecting TypeDescriptor with C# attributes related to XML?

6 Answers

For those using System.Windows.Media.Color, @bvj's solution can be simplified, leveraging the class's ToString method:

    using System.Windows.Media;

    public class XmlColor
    {
        private Color m_color;

        public XmlColor() { }
        public XmlColor(Color c) { m_color = c; }

        public static implicit operator Color(XmlColor x)
        {
            return x.m_color;
        }

        public static implicit operator XmlColor(Color c)
        {
            return new XmlColor(c);
        }

        [XmlText]
        public string Default
        {
            get { return m_color.ToString(); }
            set { m_color = (Color)ColorConverter.ConvertFromString(value); }
        }
    }
}

As before, now you can just add this before each serializable Color property:

[XmlElement(Type = typeof(XmlColor))]

By default, System.Media.Color serializes to this XML:

<DisplayColor>
  <A>255</A>
  <R>123</R>
  <G>0</G>
  <B>0</B>
  <ScA>1</ScA>
  <ScR>0.482352942</ScR>
  <ScG>0</ScG>
  <ScB>0</ScB>
</DisplayColor>

With the above conversion, it serializes to this:

<DisplayColor>#FF7B0000</DisplayColor>
Related