31 January 2020

How to deserialize Xml with different namespaces / prefixes


Specify the namespace in the child element
 [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]  
 [System.SerializableAttribute()]  
 [System.Diagnostics.DebuggerStepThroughAttribute()]  
 [System.ComponentModel.DesignerCategoryAttribute("code")]  
 [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]  
 [System.Xml.Serialization.XmlRootAttribute(Namespace= "http://search.yahoo.com/mrss/", IsNullable=false)]  
 public partial class group {  
   private groupContent[] contentField;  
   /// <remarks/>  
   [System.Xml.Serialization.XmlElementAttribute("content")]  
   public groupContent[] content {  
     get {  
       return this.contentField;  
     }  
     set {  
       this.contentField = value;  
     }  
   }  
 }  
Use the XmlElement tag and specify the namespace in the parent node
   /// <remarks/>  
   public string pubDate {  
     get {  
       return this.pubDateField;  
     }  
     set {  
       this.pubDateField = value;  
     }  
   }  
   [XmlElement("group", Namespace = "http://search.yahoo.com/mrss/")]  
   public group group  
   {  
     get  
     {  
       return this.groupField;  
     }  
     set  
     {  
       this.groupField = value;  
     }  
   }  
 }  
Note: If you want to use the Visual Studio xsd.exe to generate the C# class, you need to strip off the elements with different namespace for xsd.exe to work. You can add the separate elements manually after.