How to set xmlns when serializing object in c# How to set xmlns when serializing object in c# xml xml

How to set xmlns when serializing object in c#


What I found that works was to add this line to my class,

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://myurl.com/api/v1.0", IsNullable = true)]

and add this to my code to add namespace when I call serialize

    XmlSerializerNamespaces ns1 = new XmlSerializerNamespaces();    ns1.Add("", "http://myurl.com/api/v1.0");    xs.Serialize(xmlTextWriter, FormData, ns1);

as long as both namespaces match it works well.


The XmlSerializer type has a second parameter in its constructor which is the default xml namespace - the "xmlns:" namespace:

XmlSerializer s = new XmlSerializer(typeof(mytype), "http://yourdefault.com/");

To set the encoding, I'd suggest you use a XmlTextWriter instead of a straight StringWriter and create it something like this:

XmlWriterSettings settings = new XmlWriterSettings();settings.Encoding = Encoding.UTF8;XmlTextWriter xtw = XmlWriter.Create(filename, settings);s.Serialize(xtw, myData);

In the XmlWriterSettings, you can define a plethora of options - including the encoding.


Take a look at the attributes that control XML serialization in .NET.

Specifically, the XmlTypeAttribute may be useful for you. If you're looking to change the default namespace for you XML file, there is a second parameter to the XmlSerializer constructor where you can define that.