2

I have the following class:

public class DisplayFunction 
    {
        [System.Xml.Serialization.XmlAttribute()]
        public byte[] Color
        {
            get;
            set;
        }
        [System.Xml.Serialization.XmlAttribute()]
        public FunctionShape Shape
        {
            get;
            set;
        }
        [System.Xml.Serialization.XmlAttribute()]
        public int Id
        {
            get;
            set;
        }
}

I am using xml serializer and getting the result:

<DisplayFunctions Color="et57hQ==" Shape="Bar" Id="514" />

while i want the result to be:

 <DisplayFunctions Color="122,222,123,133" Shape="Bar" Id="514" />

How can I get that result ?

Embedd_0913
  • 16,125
  • 37
  • 97
  • 135
  • http://stackoverflow.com/questions/1075860/c-sharp-custom-xml-serialization, http://stackoverflow.com/questions/3109827/custom-xml-serialization, http://stackoverflow.com/questions/10292084/custom-xml-serialization – WhiteKnight Apr 26 '12 at 09:10

1 Answers1

1

The XML serializer is serializing the Color using byte array. So the result is odd.

My suggesting is using a public property of type string to serialize the color, and then use a conversion to convert colors to strings and vice versa.

string HtmlColor = System.Drawing.ColorTranslator.ToHtml(MyColorInstance);
string HtmlColor = System.Drawing.ColorTranslator.ToHtml(MyColorInstance);

So, you need the following:

  Color mColor;
  [XmlIgnore]
  public Color Color
  {
      get { return mColor; }
      set { mColor = value; }
  }

  [XmlElement("Color")]
  public string ColorStr
  {
      get { return ColorTranslator.ToHtml(Color); }
      set { Color = ColorTranslator.FromHtml(value); }
  }

Note: If you need to convert the Color to a byte[] you can add an additional property to get the color as a byte[] also ignoring with [XmlIgnore] attribute.

If the format provided by the ColorTranslator.ToHtml is not valid for you, you can use a custom Color translation, for example

public string ToCustomString(Color color)
{
    return string.Format("{0},{1},{2},{3}", color.A, color.R, color.G, color.B);
}

And a similar method for for parsign a color from string.

Hope it helps-

Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219