2009-11-13 5 views
14

J'ai réussi à sérialiser une classe qui hérite d'une classe de base en XML. Cependant, le XmlSerializer .NET produit un élément XML qui se présente comme suit:Empêche XmlSerializer d'émettre xsi: type sur les types hérités

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

Ceci, cependant, provoque la réception d'un service Web pour étouffer et produire une erreur qui revient à: Désolé, nous ne savons pas " DerivedType ".

Comment puis-je empêcher le XmlSerializer d'émettre l'attribut xsi: Type? Merci!

Répondre

17

Vous pouvez utiliser le XmlType attribute pour indiquer une autre valeur pour l'attribut type:

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

//produces 

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

Si vous voulez vraiment supprimer entièrement l'attribut type, vous pouvez écrire votre propre XmlTextWriter, qui sautera l'attribut lors de l'écriture (inspiré par 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

great! Très apprécié Luc. –

Questions connexes