繁体   English   中英

c#xml序列化自定义elementName

[英]c# xml serialization custom elementName

我试图将类对象序列化为xml,如下所示:

<Colors>
<Blue>
  <R>0,000</R>
  <G>0,000</G>
  <B>1,000</B>
  <A>1,000</A>
</Blue>
<Red>
  <R>1,000</R>
  <G>0,000</G>
  <B>0,000</B>
  <A>1,000</A>
</Red></Colors>

重要的是蓝色和红色不直接指定。 我有一个这样的课:

public class Color
{
    [XmlElement("R")]
    public string red;

    [XmlElement("G")]
    public string green;

    [XmlElement("B")]
    public string blue;

    [XmlElement("A")]
    public string alpha;
}

我需要的是一种创建Color类对象实例的方法,并使用不同的名称将它们序列化,如blue, red, green, anothercolor1, anothercolor2, ...也可以在程序运行时动态添加新颜色。

我知道我可以向Color类添加属性但是我无法改变xml的布局,所以我必须找到另一种方法。

有任何想法吗?

您最好的选择是使用反射来获取 Color类的所有属性并迭代它们:

public void SerializeAllColors()
{
    Type colorType = typeof(System.Drawing.Color);
    PropertyInfo[] properties = colorType.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo p in properties)
    {
        string name = p.Name;
        Color c = p.GetGetMethod().Invoke(null, null);

        //do your serialization with name and color here
    }
}

编辑:如果您无法控制更改XML格式并且您知道格式不会更改,您还可以自己对序列化进行硬编码:

在foreach循环之外:

string file = "<Colors>\n";

在循环内:

file += "\t<" + name + ">\n";
file += "\t\t<R>" + color.R.ToString() + "</R>\n";
file += "\t\t<G>" + color.G.ToString() + "</G>\n";
file += "\t\t<B>" + color.B.ToString() + "</B>\n";
file += "\t\t<A>" + color.A.ToString() + "</A>\n";
file += "\t</" + name + ">\n";

在最后:

file += "</Colors>"
using (StreamWriter writer = new StreamWriter(@"colors.xml"))
{
    writer.Write(file);
}

您可以根据需要将\\n替换为\\r\\n或使用Environment.NewLine

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM