XML Serialization and namespace prefixes

To control the namespace alias, use XmlSerializerNamespaces.

[XmlRoot("Node", Namespace="http://flibble")]
public class MyType {
    [XmlElement("childNode")]
    public string Value { get; set; }
}

static class Program
{
    static void Main()
    {
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("myNamespace", "http://flibble");
        XmlSerializer xser = new XmlSerializer(typeof(MyType));
        xser.Serialize(Console.Out, new MyType(), ns);
    }
}

If you need to change the namespace at runtime, you can additionally use XmlAttributeOverrides.


When using generated code from a schema where the types have namespaces this namespace override applies at the root level but the tags within of varying types will have the namespace associated with the class.

I had an occasion to need to use two different generated classes but have different name spaces based on which server I was talking to (don't ask not under my control).

I tried all the overrides offered here and finally gave up and used a kind of brute force method that actually worked pretty well. What I did was serialize to a string. Then use string.replace to change the namespaces then posted the stream from the string by using a stringwriter. Same on the response - capture to a string - manipulate the namespace then deserialize the string from a string writer.

It may not be elegant or use all the fancy overrides but it got the job done.