Dot-Net

防止 XmlSerializer 在繼承的類型上發出 xsi:type

  • October 25, 2013

我設法將一個從基類繼承的類序列化為 XML。但是,.NET XmlSerializer 會生成如下所示的 XML 元素:

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

但是,這會導致 Web 服務的接收端阻塞並產生錯誤,相當於:抱歉,我們不知道“DerivedType”。

如何防止 XmlSerializer 發出 xsi:Type 屬性?謝謝!

您可以使用XmlType 屬性為 type 屬性指定另一個值:

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

//produces

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

如果你真的想完全去掉type屬性,你可以自己寫個XmlTextWriter,寫的時候會跳過這個屬性(靈感來源於這篇博文):

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)

引用自:https://stackoverflow.com/questions/1729711