XmlSerializer和xsi:type

时间:2012-11-24 17:27:20

标签: c# .net xml serialization

我有以下课程,请注意B继承A

[XmlInclude(typeof(B))]
public class A
{...}

public class B : A
{...}

当序列化B的实例时,会添加xsi:type属性:

<A xsi:type="B">

为什么会这样?结果应该只是<B>

这是序列化的代码:

var b = new B();
using (var writer = new XmlTextWriterFull(stream, Encoding.UTF8))
{
    writer.Formatting = Formatting.Indented;
    var s = new XmlSerializer(typeof(B));
    s.Serialize(writer, b);
}

我序列化的其他类不会发生这种情况。是因为这些类位于不同的命名空间中吗?

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

尝试这种方法:

    B b = new B();
    byte[] data = SerializeObject(b);
    File.WriteAllBytes("test.xml", data);

以下是序列化的代码

    /// <summary>
    /// Serialize object
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    internal static byte[] SerializeObject(object data)
    {
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        //empty namespace...
        ns.Add("", "");
        XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
        MemoryStream memStream = new MemoryStream();
        xmlSerializer.Serialize(memStream, data, ns);
        byte[] result = memStream.ToArray();
        memStream.Dispose();
        return result;
    }

序列化结果是:

<?xml version="1.0"?>
<B>
</B>