简体   繁体   中英

c# xml serialization custom elementName

I am trying to serialize an class object into xml that looks like this:

<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.

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.

Any ideas?

Your best bet would be to use reflection to get all the properties of the Color class and iterate through them:

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:

Outside the foreach loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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