【发布时间】: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没有意义,应该是
<Colors><Color Name="Red">..</Color></Colors> -
@HenkHolterman:目前我没有存储名称,如果需要,我会在颜色类中进行。我还考虑过使用第二个类并使用颜色类对象和其中的名称制作一个 sortedlist
,但我无法序列化 sortedlist 或者我错过了什么? -
@BasB:我知道这个 xml 没有意义。我会按照你描述的方式做,但我不能改变 xml 的布局。
-
亲爱的 Benedikt H., 您想更改 xml 文本的可读性吗?如果是,您可以尝试使用 xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.Indentation = 3;在将字符串写入文本之前。
标签: c# xml serialization xmlserializer