【问题标题】:c# xml serialization custom elementNamec# xml序列化自定义elementName
【发布时间】:2012-01-31 19:28:15
【问题描述】:

我正在尝试将一个类对象序列化为如下所示的 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 的布局,所以我必须找到另一种方法。

有什么想法吗?

【问题讨论】:

  • 您如何/在哪里存储名称?它必须使用特定的序列化程序吗?
  • 提供的XML没有意义,应该是&lt;Colors&gt;&lt;Color Name="Red"&gt;..&lt;/Color&gt;&lt;/Colors&gt;
  • @HenkHolterman:目前我没有存储名称,如果需要,我会在颜色类中进行。我还考虑过使用第二个类并使用颜色类对象和其中的名称制作一个 sortedlist,但我无法序列化 sortedlist 或者我错过了什么?
  • @BasB:我知道这个 xml 没有意义。我会按照你描述的方式做,但我不能改变 xml 的布局。
  • 亲爱的 Benedikt H., 您想更改 xml 文本的可读性吗?如果是,您可以尝试使用 xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.Indentation = 3;在将字符串写入文本之前。

标签: c# xml serialization xmlserializer


【解决方案1】:

最好的办法是对 Color 类的 get all the properties 使用反射并遍历它们:

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\nEnvironment.NewLine

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多