2009-11-13 55 views
14

我已經設法將從基類繼承到XML的類序列化。然而,在.NET XmlSerializer的產生如下所示的XML元素:防止XmlSerializer在繼承類型上發出xsi:type

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

然而,這會導致網絡服務的接收端嗆,併產生相當於一個錯誤:對不起,我們不知道。「 DerivedType」。

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

回答

17

可以使用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) 
+1

太棒了!非常感謝Luc。 – 2009-11-13 18:06:21