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

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.