【问题标题】:Serialize member types without using XmlInclude in .NET在 .NET 中不使用 XmlInclude 序列化成员类型
【发布时间】:2013-06-25 11:54:58
【问题描述】:

我在 .NET 中执行 XML 序列化

我有以下课程

public class MainClass
{
    public ClassA A;
}

public class ClassA { }

public class ClassB : ClassA { }

public class ClassC : ClassA { }

当我在 MainClass 的对象上调用 XmlSerializerSerialize 方法时,我收到异常建议使用 XmlInclude 属性。我不想使用属性选项。

Serialize 方法有一个重载,它采用 Type 数组来指定正在执行序列化的类型(上例中为 MainClass)的子类型。使用这个重载我们可以避免使用XmlInclude 属性标记类的需要。

可以用被序列化的类型(上例中的 MainClass)的成员来做类似的事情吗?

【问题讨论】:

    标签: c# .net xml serialization xml-serialization


    【解决方案1】:
    var ser = new XmlSerializer(typeof(MainClass),
        new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) });
    ser.Serialize(writer, new MainClass { A = new ClassB() });
    

    结果:

    <MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <A xsi:type="ClassB" />
    </MainClass>
    

    或者,您可以通过编程方式添加属性:

    var overrides = new XmlAttributeOverrides();
    // Add [XmlElement]'s to MainClass.A
    overrides.Add(typeof(MainClass), "A", new XmlAttributes
    {
        XmlElements = {
            new XmlElementAttribute() { Type = typeof(ClassA) },
            new XmlElementAttribute() { Type = typeof(ClassB) },
            new XmlElementAttribute() { Type = typeof(ClassC) },
        }
    });
    
    var ser = new XmlSerializer(typeof(MainClass), overrides, null, null, null);
    ser.Serialize(writer, new MainClass { A = new ClassB() });
    

    结果:

    <MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <ClassB />
    </MainClass>
    

    【讨论】:

    • 我想避免属性,正如我在问题中所说的那样。我知道这个解决方案。有什么方法可以在不使用属性的情况下完成?
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2014-06-07
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2019-03-05
    相关资源
    最近更新 更多