阻止XmlSerializer在继承的类型上发出xsi:type

时间:2009-11-13 14:55:38

标签: .net xml xml-serialization

我设法将从基类继承的类序列化为XML。但是,.NET XmlSerializer生成的XML元素如下所示:

<BaseType xsi:Type="DerivedType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

但是,这会导致Web服务的接收端出现阻塞并产生错误,该错误相当于:抱歉,我们不知道“DerivedType”。

如何阻止XmlSerializer发出xsi:Type属性?谢谢!

1 个答案:

答案 0 :(得分:18)

您可以使用XmlType attribute为type属性指定另一个值:

[XmlType("foo")]
public class DerivedType {...}

//produces

<BaseType xsi:type="foo" ...>

如果你真的想要完全删除type属性,你可以编写自己的XmlTextWriter,它会在写作时跳过该属性(受this blog entry启发):

public class NoTypeAttributeXmlWriter : XmlTextWriter
{
    public NoTypeAttributeXmlWriter(TextWriter w) 
               : base(w) {}
    public NoTypeAttributeXmlWriter(Stream w, Encoding encoding) 
               : base(w, encoding) { }
    public NoTypeAttributeXmlWriter(string filename, Encoding encoding) 
               : base(filename, encoding) { }

    bool skip;

    public override void WriteStartAttribute(string prefix, 
                                             string localName, 
                                             string ns)
    {
        if (ns == "http://www.w3.org/2001/XMLSchema-instance" &&
            localName == "type")
        {
            skip = true;
        }
        else
        {
            base.WriteStartAttribute(prefix, localName, ns);
        }
    }

    public override void  WriteString(string text)
    {
        if (!skip) base.WriteString(text);
    }

    public override void WriteEndAttribute()
    {
        if (!skip) base.WriteEndAttribute();
        skip = false;
    }
}
...
XmlSerializer xs = new XmlSerializer(typeof(BaseType), 
                                     new Type[] { typeof(DerivedType) });

xs.Serialize(new NoTypeAttributeXmlWriter(Console.Out), 
             new DerivedType());

// prints <BaseType ...> (with no xsi:type)