Search code examples
c#xmlxml-serializationxmlserializer

Remove namespace xml of a property during XML serialization


I have a object like this:

public class A {
 public int ID {get; set;} 
 public Name PName {get; set;} 
}

[XmlType(Namespace = "somenamespace")]
public class Name{
 public string FName {get; set;}
 public string LName {get; set;}
}

When I serialize this I get below XML:

<A>
 <ID>1</ID>
 <PName>
  <FName xmlns="somenamespace">First Name</FNAME>
  <LName xmlns="somenamespace">Last Name</LNAME>
 </PName>
</A>

Is there a way to get rid of the namespace of class "Name" during the serialization?

Obviously I cannot just remove XML type attribute of class "Name".

I have already tried this solution (first answer), but it did not work for me. Omitting all xsi and xsd namespaces when serializing an object in .NET?

Many thanks in advance,

Ash.


Solution

  • If you don't own the type Name, you can still control its serialisation by overriding the XML attributes using XmlAttributeOverrides when creating the serialiser.

    For example:

    var overrides = new XmlAttributeOverrides();
    
    overrides.Add(typeof(Name), new XmlAttributes());
    
    var serializer = new XmlSerializer(
        typeof(A), overrides, null, null, string.Empty);
    

    See this fiddle for a working demo.