C # xml serialization custom elementName

I am trying to serialize a class object in 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 of blue and red are not directly indicated. 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; } 

I need a way to instantiate an object of the Color class and serialize it with different names, for example blue, red, green, anothercolor1, anothercolor2, ... it should also be possible to dynamically add new colors at runtime.

I know that I can add attributes to the Color class, but I cannot change the xml layout, so I need to find another way.

Any ideas?

+4
source share
1 answer

It would be best 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 cannot change the XML format, and know that the format will not change, you can simply simply copy the serialization yourself:

Outside of the foreach loop:

 string file = "<Colors>\n"; 

Inside 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 Environment.NewLine of your choice

0
source

Source: https://habr.com/ru/post/1388925/


All Articles