2012-04-26 20 views
2

我有以下類:如何在C#中使用xmlserializer自定義xml?

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; 
     } 
} 

我使用XML序列化和獲得的結果:

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

,而我希望得到的結果是:

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

哪有我得到那個結果?

+0

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 2012-04-26 09:10:27

回答

1

XML串行器使用字節數組序列化Color。所以結果很奇怪。

我的建議是使用類型爲string的公共屬性來序列化顏色,然後使用轉換將顏色轉換爲字符串,反之亦然。

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

所以,你需要以下條件:

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); } 
    } 

注意:如果您需要將Color轉換爲byte[]你可以添加額外的屬性來獲取顏色作爲byte[]也忽視與[XmlIgnore]屬性。

如果由ColorTranslator.ToHtml提供的格式是無效的,你可以使用自定義色彩轉換,例如

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

以及爲parsign從字符串顏色類似的方法。

希望它helps-

相關問題