简体   繁体   English

将枚举序列化/反序列化为元素名称(而不是元素的内容/值)

[英]serialize/deserialize enum as element name (rather than element content/value)

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. 其中<green/>可能是<red/><blue/>等-非常大(但有限)的集合。

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元素value ,而不必将所有值(这是一个很大的集合)重新键入为空类。名称,还是诉诸自定义序列化(我想避免这种情况,因为序列化的类包含许多其他成员,默认情况下它们完美地序列化了)?

(I can't change the schema, it's third-party). (我无法更改架构,它是第三方)。

No, this is not supported by simply decorading your classes with [Xml*] attributes. 不,仅通过使用[Xml*]属性对类进行装饰是不支持的。 You will have to implement IXmlSerializable on Something and do it yourself. 您将必须在Something上实现IXmlSerializable并自己完成。 Note that in most cases you don't have to bother with the GetSchema method; 注意,在大多数情况下,您不必费心使用GetSchema方法。 implementing ReadXml and WriteXml is just fine. 实现ReadXmlWriteXml很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM