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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…