在C#中以特定格式序列化XML



我有类似的类:

[System.Serializable]
public class UIColor
{
    public UIColor()
    {
    }
    public UIColor(double red, double green, double blue, double alpha)
    {
        r = (float)red;
        g = (float)green;
        b = (float)blue;
        a = (float)alpha;
    }
    public UIColor(double white, double alpha)
    {
        r = (float)white;
        g = (float)white;
        b = (float)white;
        a = (float)alpha;
    }
    [System.Xml.Serialization.XmlElement("r", typeof(float))]
    public float r
    {
        get;
        set;
    }
    [System.Xml.Serialization.XmlElement("g", typeof(float))]
    public float g
    {
        get;
        set;
    }
    [System.Xml.Serialization.XmlElement("b", typeof(float))]
    public float b
    {
        get;
        set;
    }
    [System.Xml.Serialization.XmlElement("alpha", typeof(float))]
    public float a
    {
        get;
        set;
    }
}

以及类似类的许多实例:

class Colors
{
[XmlElement("Col1")]
  UIColor Col1;
[XmlElement("Col2")]
  UIColor Col2;
  //etc etc
}

我想做的是以以下格式将类颜色序列化为XML:

<Color name="Col1" r="1" g="1" b="1" alpha="1"/>
<Color name="Col2" r="2" g="2" b="2" alpha="2"/>

当前序列形式的方式就像:

<Col1>
<r>1</r>
//etc etc

您的原始类应该看起来像:

[System.Serializable]
[System.Xml.Serialization.XmlRoot("Color")]
public class UIColor
{
    public UIColor()
    {
        name = "Col1"
    }
    public UIColor(double red, double green, double blue, double alpha)
    {
        r = (float)red;
        g = (float)green;
        b = (float)blue;
        a = (float)alpha;
        name = "Col1";
    }
    public UIColor(double white, double alpha)
    {
        r = (float)white;
        g = (float)white;
        b = (float)white;
        a = (float)alpha;
        name = "Col1";
    }
    [System.Xml.Serialization.XmlAttribute]
    public string name
    {
        get;
        set;
    }

    [System.Xml.Serialization.XmlAttribute]
    public float r
    {
        get;
        set;
    }
    [System.Xml.Serialization.XmlAttribute]
    public float g
    {
        get;
        set;
    }
    [System.Xml.Serialization.XmlAttribute]
    public float b
    {
        get;
        set;
    }
    [System.Xml.Serialization.XmlAttribute("alpha")]
    public float a
    {
        get;
        set;
    }
}

和序列化代码:

using (System.IO.TextWriter writer = new System.IO.StreamWriter(@"C:temptest.xml"))
{
      System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(UIColor));
      System.Xml.Serialization.XmlSerializerNamespaces namspace = new XmlSerializerNamespaces();
      namespace.Add("", "");
      xml.Serialize(writer, new UIColor(), namespace);
}

,OUT XML将产生:

<?xml version="1.0" encoding="utf-8"?>
<Color name="Col1" r="0" g="0" b="0" alpha="0" />

最新更新