Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize an object to XML

I have a C# class that I have inherited. I have successfully "built" the object. But I need to serialize the object to XML. Is there an easy way to do it?

It looks like the class has been set up for serialization, but I'm not sure how to get the XML representation. My class definition looks like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)] public partial class MyObject {   ... } 

Here is what I thought I could do, but it doesn't work:

MyObject o = new MyObject(); // Set o properties string xml = o.ToString(); 

How do I get the XML representation of this object?

like image 843
user462166 Avatar asked Nov 08 '10 11:11

user462166


People also ask

What is serialization in XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

What is XML serialization in Java?

Serialization of Java Objects to XML can be done using XMLEncoder, XMLDecoder. Java Object Serialization feature was introduced in JDK 1.1. Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network.

Is XML a serialization format?

XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it is deserialized into an object of the same type.


2 Answers

You have to use XmlSerializer for XML serialization. Below is a sample snippet.

 XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));  var subReq = new MyObject();  var xml = "";   using(var sww = new StringWriter())  {      using(XmlWriter writer = XmlWriter.Create(sww))      {          xsSubmit.Serialize(writer, subReq);          xml = sww.ToString(); // Your XML      }  } 

As per @kiquenet request for generic class:

public class MySerializer<T> where T : class {     public static string Serialize(T obj)     {         XmlSerializer xsSubmit = new XmlSerializer(typeof(T));         using (var sww = new StringWriter())         {             using (XmlTextWriter writer = new XmlTextWriter(sww) { Formatting = Formatting.Indented })             {                 xsSubmit.Serialize(writer, obj);                 return sww.ToString();             }         }     } } 

usage:

string xmlMessage = MySerializer<MyClass>.Serialize(myObj); 
like image 123
RameshVel Avatar answered Oct 20 '22 08:10

RameshVel


I modified mine to return a string rather than use a ref variable like below.

public static string Serialize<T>(this T value) {     if (value == null)     {         return string.Empty;     }     try     {         var xmlserializer = new XmlSerializer(typeof(T));         var stringWriter = new StringWriter();         using (var writer = XmlWriter.Create(stringWriter))         {             xmlserializer.Serialize(writer, value);             return stringWriter.ToString();         }     }     catch (Exception ex)     {         throw new Exception("An error occurred", ex);     } } 

Its usage would be like this:

var xmlString = obj.Serialize(); 
like image 30
Kwex Avatar answered Oct 20 '22 09:10

Kwex