Friday, October 11, 2019

XML Serialization: How to serialize an object to xml in C#


Serialization is the process of converting an object into a format (for example stream of bytes) that can be stored (for example in database, in a file) or transmitted over network. The reverse process is called De-serialization.

How to serialize an object to xml in C#

There are various data Serialization formats to convert object into serializable formats (for example bytes, XML, JSON)


 1.   XML serialization:
XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document

2.   Binary serialization :
Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network streams.

3.   JSON serialization :
JSON serialization is used to serialize objects into JSON-encoded data, which is very efficient to transfer the small amount of data between server and client browser 


In this blog, we will discuss about the XML Serialization and how to convert C # object into XML format.

Microsoft provide the XmlSerializer class to serialize the .net Type into XML format and XmlTextWriter to output the XML string.

Here is a C# example of XML serialization

  public class Serializer
    {
        public string ToXML<T>(T Object)
        {
            StringWriter  stringWriter = new StringWriter();
            XmlTextWriter xmlTextWriter = null;

            XmlSerializer serializer = new XmlSerializer(Object.GetType());
            xmlTextWriter = new XmlTextWriter(stringWriter);
            serializer.Serialize(xmlTextWriter, Object);

            return stringWriter.ToString();
        }
    }


Now let’s create a .net object ‘Order’ for XML serialization   

   public class Order
    {
        public int OrderNumber { get; set; }
        public string Item { get; set; }
        public string User { get; set; }
    }

Create an instance of Order Class and try to convert order object into XML

     Order order = new Order {
Item = "Iphone 7",
 OrderNumber = 12,
 User = "Smith"
};

     Serializer serializer = new Serializer();
     string xml = serializer.ToXML<Order>(order);

When run the above code, you will get below XML string from Order instance.



Other related posts:

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...