4

我有以下课程,请注意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);
}

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

我该如何解决这个问题?

4

1 回答 1

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>
于 2012-11-24T17:48:07.970 回答