I need to deserialize/serialize XML which looks like this:
我需要反序列化/序列化XML,如下所示:
<color>
<green/>
</color>
where <green/>
may be <red/>
, <blue/>
etc. - very large (but limited) set.
其中
I'd like to describe it as simple enum in my code:
我想在我的代码中将其描述为简单的枚举:
enum ColorName
{
[XmlEnum("red")]
Red,
[XmlEnum("green")]
Green,
[XmlEnum("blue")]
Blue,
...
etc.
}
But, if I write my object model like this:
但是,如果我像这样写我的对象模型:
class Color
{
[XmlElement("name")]
public ColorName ColorName;
}
class Something
{
[XmlElement("color")]
public Color Color;
}
enum gets into XML as a value, rather than element name:
枚举作为值而不是元素名称进入XML:
<color>
<name>green</name>
</color>
Is there any way to get enum value written into XML element name (see the first XML snippet - that's the goal), rather than XML element value, without having to re-type all the values (it's a very large set) as empty class names, or resorting to custom serialization (I would like to avoid it, because serialized class contains a lot of other members, which are perfectly serialized by default)?
是否有任何方法可以将枚举值写入XML元素名称(请参阅第一个XML片段 - 这是目标),而不是XML元素值,而不必将所有值(它是一个非常大的集合)重新键入为空类名称,或诉诸自定义序列化(我想避免它,因为序列化的类包含很多其他成员,默认情况下完全序列化)?
(I can't change the schema, it's third-party).
(我不能改变架构,它是第三方)。
1 个解决方案
#1
0
No, this is not supported by simply decorading your classes with [Xml*]
attributes. You will have to implement IXmlSerializable
on Something
and do it yourself. Note that in most cases you don't have to bother with the GetSchema
method; implementing ReadXml
and WriteXml
is just fine.
不,只需使用[Xml *]属性解析您的类就不支持此功能。你必须在Something上实现IXmlSerializable并自己动手。请注意,在大多数情况下,您不必费心使用GetSchema方法;实现ReadXml和WriteXml就好了。
#1
0
No, this is not supported by simply decorading your classes with [Xml*]
attributes. You will have to implement IXmlSerializable
on Something
and do it yourself. Note that in most cases you don't have to bother with the GetSchema
method; implementing ReadXml
and WriteXml
is just fine.
不,只需使用[Xml *]属性解析您的类就不支持此功能。你必须在Something上实现IXmlSerializable并自己动手。请注意,在大多数情况下,您不必费心使用GetSchema方法;实现ReadXml和WriteXml就好了。