Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 388
John Avatar asked Apr 02 '10 15:04

John


People also ask

How to serialize list of object to XML in c#?

How to Serialize a Simple Object to XML in C# The Patient class contains the necessary information for a hospital patient. Here, we create an XMLSerializer object that will serialize objects of type Patient . The Serialize() method transforms the object into XML.

What is the correct way of using XML serialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.


1 Answers

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.

like image 166
John Avatar answered Oct 16 '22 20:10

John