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

时间:2017-02-20 05:36:08

标签: 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
}

我想要做的是按以下格式将类Color序列化为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

1 个答案:

答案 0 :(得分:2)

您的原始课程应如下所示:

[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:\temp\test.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" />