可以使用XmlType attribute指定類型屬性的另一個值:
[XmlType("foo")]
public class DerivedType {...}
//produces
<BaseType xsi:type="foo" ...>
如果你真的想徹底刪除類型的屬性,你可以寫自己的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)
太棒了!非常感謝Luc。 – 2009-11-13 18:06:21