views:

68

answers:

3

I am serializing an object in my ASP.net MVC program to an xml string like this;

StringWriter sw = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(mytype));
s.Serialize(sw, myData);

Now this give me this as the first 2 lines;

<?xml version="1.0" encoding="utf-16"?>
<GetCustomerName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;

my question is, How can I change the xmlns and the encoding type, when serializing?

Thanks

+1  A: 

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.

LBushkin
+2  A: 

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.

marc_s
A: 

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.

John