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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With