繁体   English   中英

使用属性值的XML序列化派生类型

[英]XML Serialization Derived Types using value of an Attribute

我正在修改一组要序列化的类,但有一个问题,我找不到答案。 旧的类有一个很大的类叫做Control,它通过ControlType属性进一步分类

enum ControlType
{
    ControlType1 = 0,
    ControlType2 = 1
}

public class Control
{
    [XmlAttribute("a")]
    public string a { get; set; }

    [XmlAttribute("b")]
    public string b { get; set; }

    [XmlAttribute("Type")]
    public ControlType Type {get; set;)
}

在上面的简化示例中,原始设计者没有将类分离为子类。 我们真正想要的是

class baseControl
{
     [XmlAttribute("Type")]
     public ControlType Type {get; set;}
}

class Control1 : baseControl
{
    [XmlAttribute("a")]
    public string a { get; set; }
}

class Control2 : baseControl
{ 
    [XmlAttribute("b")]
    public string b { get; set; }
}

我们想要分离出类但我们希望原始的xml兼容

在旧的层次结构中,所有控件类型(由ControlType定义)都被序列化为

<Control Type="ControlType1" a="xxxx" />
<Control Type="ControlType2" b="xxxxx" />

如果我们明显使用新结构,新结构将会是这样的

<Control1 Type="ControlType1" a="xxxx" />
<Control2 Type="ControlType2" b="xxxxx" />

但我们确实希望将所有新派生类序列化为“Control”,当我们反序列化时,我们希望根据Attribute的值将分配的类型更改为派生类型。

这可能吗?

实现此类行为的唯一机会是在对应于周围元素的类上实现IXmlSerializable ,并提供自定义(反)序列化行为。

public class ControlContainer : IXmlSerializable
{
    // a single / array of / list of BaseControls
    public BaseControl Control { get; set; }

    // … any other properties

    // … implement IXmlSerializable here to have Control 
    // and any other properties (de)serialized
}

暂无
暂无

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

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