John
John

Reputation: 1922

How to set xmlns when serializing object in c#

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

Upvotes: 11

Views: 20262

Answers (3)

John
John

Reputation: 1922

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.

Upvotes: 15

marc_s
marc_s

Reputation: 754488

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.

Upvotes: 11

LBushkin
LBushkin

Reputation: 131676

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.

Upvotes: 1

Related Questions