内部有各种类型的对象模型

Object model with various type inside

像这样序列化和反序列化 XML 的最佳对象模型是什么:

<root>
    <header>
        <elementA>Example</elementA>
        <elementB>Test</elementB>
    </header>
    <content>
        <elementC>foo</elementC>
        <variousTypeA>
            <itemA>Test</itemA>
            <itemB>Test</itemB>
            <itemC>Test</itemC>
        </variousTypeA>
    </content>
</root>

我的问题是像这样用另一个更新 variousTypeA :

<root>
    <header>
        <elementA>Example</elementA>
        <elementB>Test</elementB>
    </header>
    <content>
        <elementC>foo</elementC>
        <variousTypeB>
            <itemZ>Test</itemZ>
            <itemY>Test</itemY>
            <itemX>Test</itemX>
        </variousTypeB>
    </content>
</root>

生成 XML 的最佳选择是什么
XmlSerializer xmlSerializer = new XmlSerializer(typeof(variousTypeA));

XmlSerializer xmlSerializer = new XmlSerializer(typeof(variousTypeB));

但没有重复共同的元素...

架构必须可用于 C# XmlSerializer class。 您有对象模型要提出吗?

一个解决方案是创建一个 class 层次结构,对应于各种可能的 <content> 元素,如下所示:

public abstract class ContentBase
{
    public string elementC { get; set; }
}

public class ContentA : ContentBase
{
    public VariousTypeA variousTypeA { get; set; }
}

public class ContentB : ContentBase
{
    public VariousTypeB variousTypeB { get; set; }
}

然后,对于<root>元素对应的POCO,创建一个class层次结构,其中基类型指定公共属性,派生类型是泛型,表示[=的具体类型16=] 对象,约束为类型 ContentBase:

public abstract class RootBase
{
    public Header header { get; set; }

    [XmlIgnore]
    // The following provides get-only access to the specific content of this root
    public abstract ContentBase BasicContent { get; }
}

public class Header
{
    public string elementA { get; set; }
    public string elementB { get; set; }
}

[XmlRoot(ElementName = "root")]
public class Root<TContent> : RootBase 
    where TContent : ContentBase
{
    public TContent content { get; set; }

    public override ContentBase BasicContent { get { return content; } }
}

然后像这样使用它:

var rootA = (Root<ContentA>)new XmlSerializer(typeof(Root<ContentA>)).Deserialize(new StringReader(xmlStringA));

var rootB = (Root<ContentB>)new XmlSerializer(typeof(Root<ContentB>)).Deserialize(new StringReader(xmlStringB));

此设计允许共享与 <root><content> 的公共元素相关的代码。

示例 fiddle.