Alex Rivera | Logout

How to set xmlns when serializing object in c#

Asked 2010-04-02T15:08:14.873
11

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">

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

Thanks

Edit
Report

1 Answer

11

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.

answered 2010-04-02T15:12:13.307

Your Answer