Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent XmlSerializer from emitting xsi:type on inherited types

I have managed to serialize a class that inherits from a base class to XML. However, the .NET XmlSerializer produces an XML element that looks as follows:

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

This, however, causes the receiving end of a web service to choke and produce an error that amounts to: sorry we do not know "DerivedType".

How can I prevent the XmlSerializer from emitting the xsi:Type attribute? Thanks!

like image 772
martijn_himself Avatar asked Nov 13 '09 14:11

martijn_himself


1 Answers

You can use the XmlType attribute to specify another value for the type attribute:

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

//produces

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

If you really want to entirely remove the type attribute, you can write your own XmlTextWriter, which will skip the attribute when writing (inspired by 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)
like image 64
Luc Touraille Avatar answered Nov 15 '22 23:11

Luc Touraille