简体   繁体   English

c#xml序列化自定义elementName

[英]c# xml serialization custom elementName

I am trying to serialize an class object into xml that looks like this: 我试图将类对象序列化为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>

The important part is that the colors blue and red are not specified directly. 重要的是蓝色和红色不直接指定。 I have a class like this: 我有一个这样的课:

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

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

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

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

What I need is a way to create instances of the Color class object and serialize them with different names like blue, red, green, anothercolor1, anothercolor2, ... also it must be posible to add new colors dynamicly while the programm runs. 我需要的是一种创建Color类对象实例的方法,并使用不同的名称将它们序列化,如blue, red, green, anothercolor1, anothercolor2, ...也可以在程序运行时动态添加新颜色。

I know I could add attributes to the Color class but I cant change the layout of the xml, so I have to find another way. 我知道我可以向Color类添加属性但是我无法改变xml的布局,所以我必须找到另一种方法。

Any ideas? 有任何想法吗?

Your best bet would be to use reflection to get all the properties of the Color class and iterate through them: 您最好的选择是使用反射来获取 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
    }
}

Edit: If you aren't in control to change the XML format and you know the format won't change, you could additionally just hardcode the serialization yourself: 编辑:如果您无法控制更改XML格式并且您知道格式不会更改,您还可以自己对序列化进行硬编码:

Outside the foreach loop: 在foreach循环之外:

string file = "<Colors>\n";

Within the loop: 在循环内:

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

And at the very end: 在最后:

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

Replace \\n with \\r\\n or with Environment.NewLine as you please 您可以根据需要将\\n替换为\\r\\n或使用Environment.NewLine

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

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