0

我正在.NET 中执行 XML 序列化

我有以下课程

public class MainClass
{
    public ClassA A;
}

public class ClassA { }

public class ClassB : ClassA { }

public class ClassC : ClassA { }

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

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

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

4

1 回答 1

2
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>
于 2013-06-25T12:52:05.273 回答