簡體   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