C#.Net – XML serialization in C#

XML serialization,XML,Why we need serialization? ,Basic Serialization,What is C# XML serialization?,XML serialization,Serialization,c# object serialization
Share it:
Why we need serialization?




Why we need serialization?

Well, the simple answer to this is – to persist an object and save it in a specified storage location like a physical file or DataBase.



Serialization converts an object into a stream and then uses it either to save it in a file or to send/transport over any communication channel. Serialization in c# is very easy because c# with .net framework has several c# serialization techniques. Few of them are listed below, however, in this article, we are going to focus on the C# XML serialization technique only.



1) XML serialization

2) Binary serialization

3) SOAP serialization



What is C# XML serialization?

As the name suggests, a serialization technique in which an object will be converted/saved into XML format or stream. To use serialization in XML we need XmlSerializer class. This class is derived from System.Xml.Serialization. Serialize and Deserialize are the two most important methods that we use to serialize an object to XML and then again deserialize into an object.


Things to remember while using XML serialization and deserialization in c#

1) Only public objects can be serialized in XML serialization. And hence it is called Shallow serialization.

2) Classes inherited from IEnumerable and ICollection can also be serialized, however, it serializes only collections and not public properties.


3) Private or read-only properties, Methods, Indexers cannot be serialized using this XML serialization.
Let see different scenarios to understand how c# serializes an object to XML.

A. Basic Serialization::


Let’s take a simple example. Take a look at below class –
public class BasicSerialization
{
   public String name = “C# Tutorials”;
}

BasicSerialization is a class that has only a public field “name” with default value “c# tutorial”. 

Now use below code (method) to serialize above class –

private static void BasicSerializationMethod()
{
     // Create an instance of BasicSerialization class.
     BasicSerialization serializeObject = new BasicSerialization();
     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(BasicSerialization));
     // Create an instance of stream writer.
     TextWritertxtWriter = new StreamWriter(@”C:\Serialization Examples\BasicSerialization.xml“);
nbsp;    // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, serializeObject);
     // Close the stream writer
     txtWriter.Close();
}


What we have done here –
 i) First, we have created an object of a class BasicSerialization, the object which we are going to serialize.
 ii) Created an object of XmlSerializerof type BasicSerialization.This object will then be used to serialize. 
iii) Created an object of Text StreamWriter to save files in a physical location. iv) Called the “Serialize” method of XML serializer class to happen an XML serialization of the above-mentioned object. 
v) Closed the TextWriter.



After serialization of an instance of the above class, the XML at location highlighted above would look alike –


<?xml version=“1.0“ encoding=“utf-8“?>
<BasicSerialization>
  <name>C# Tutorials</name>
</BasicSerialization>
Note: you might also get XML namespaces with the root element.

B. Basic Serialization with more properties in class- In this example, we are creating a new class “Camera” with two properties



public class Camera { public string MakeModel { get; set; } 
public string Price { get; set; } }
Now, serialize an object of this class using the following code –
private static void SerializationCamera()
{
     // Create an instance of Camera class.
     Camera camera = newCamera();
     // Assing values to it’s properties
     camera.MakeModel = “Canon EOS-1D”;
     camera.Price = “$ 5219″;
     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(Camera));
     // Create an instance of stream writer.
     TextWriter txtWriter = newStreamWriter(@”C:\Serialization Examples\BasicSerializationCamera.xml“);
     // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, camera);
     // Close the stream writer
     txtWriter.Close();
}

Here we are serializing the same way as we did in the first example. The output XML of this will look alike –


<?xml version=“1.0“ encoding=“utf-8“?>
<Camera xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
                  xmlns:xsd=“http://www.w3.org/2001/XMLSchema“>
  <MakeModel>Canon EOS-1D</MakeModel>
  <Price>$ 5219</Price>
</Camera>


C. Serialization with XmlElement - If you closely look at the XML file in the above example, you will observe that the element names in the XML file are the same as property names in the class definition. We can also define the element names with the use of the XmlElement attribute. Look at below code, which is same as given above – the only difference is that we used XmlElement with property definition –

public class Camera { [XmlElement("CameraName")]
 public string MakeModel { get; set; }
 [XmlElement("CameraPrice")] 
 public string Price { get; set; 
} }
Now again call the SerializationCamera() Method to generate the XML file as below –
<?xml version=“1.0“ encoding=“utf-8“?>
<Camera xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance“
 xmlns:xsd=“http://www.w3.org/2001/XMLSchema“>
  <CameraName>Canon EOS-1D</CameraName>
  <CameraPrice>$ 5219</CameraPrice>
</Camera>

Observe the element names here. MakeModel is saved as CameraName and Price is saved as CameraPrice.


D. Serialize an array of objects –



To understand how to serialize an array of objects, again take the same example of the Camera class given above.
Use the following method to Serialize the array of a Camera class.



private static void SerializationCameraObjects()
{
     //Create first instance of Camera class.
     Camera camera1 = newCamera();
     camera1.MakeModel = “Canon EOS-1D”;
     camera1.Price = “$ 5219″;
     //Create second instance of Camera class.
     Camera camera2 = newCamera();
     camera2.MakeModel = “Canon EOS-1D Mark IV”;
     camera2.Price = “$ 5000″;
     // Create an array of Camera
     Camera[] cameras = new Camera[2];
     cameras[0] = camera1;
     cameras[1] = camera2;
     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(Camera[]));
     // Create an instance of a stream writer.
     TextWriter txtWriter = newStreamWriter(@”C:\Serialization Examples\SerializationArrayOfObj.xml”);
     // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, cameras);
     // Close the stream writer
     txtWriter.Close();
}
Look at the highlighted part to understand what we have changed from the last source code.
The output will look alike –
<?xml version=“1.0“ encoding=“utf-8“?>
<ArrayOfCamera xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance“ xmlns:xsd=“http://www.w3.org/2001/XMLSchema“>
  <Camera>
    <CameraName>Canon EOS-1D</CameraName>
    <CameraPrice>$ 5219</CameraPrice>
  </Camera>
  <Camera>
    <CameraName>Canon EOS-1D Mark IV</CameraName>
    <CameraPrice>$ 5000</CameraPrice>
  </Camera>
</ArrayOfCamera>

E. Serialize a DataSet – Let’s assume we have a dataset that has a DataTable with two columns and two rows. This DataSet stores CameraDetails as shown in below table –
Camera Make Model
Price
Canon EOS-1D
$ 5219
Canon EOS-1D Mark IV
$ 5000


We would use the below method to serialize DataSet in XML –
private static void DataSetSerialization()
{
     // Create and instance of XmlSerializer class.
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
     // Create a DataSet; adds a table, column, and ten rows.
     DataSet cameraDS = newDataSet(“Camera”);
     // Create DataTable.
     DataTable cameraDT = newDataTable(“CameraDetails”);
     // Specify columns of a DataTable
     cameraDT.Columns.Add(“MakeModel”); //Column1
     cameraDT.Columns.Add(“Price”); //Column2s
     // Add rows in DataTable
     cameraDT.Rows.Add(“Canon EOS-1D”, “$ 5219″);
     cameraDT.Rows.Add(“Canon EOS-1D Mark IV”, “$ 5000″);
     // Add DataTable in DataSet
     cameraDS.Tables.Add(cameraDT);
     // Create an instance of stream writer.
     TextWriter txtWriter = newStreamWriter(@”C:\Serialization Examples\DataSetSerialization.xml“);
     // Serialize the instance of BasicSerialization
     xmlSerializer.Serialize(txtWriter, cameraDS);
     // Close the stream writer
     txtWriter.Close();
}

The output of the above code will be like below XML –

<?xml version=“1.0“ encoding=“utf-8“?>
<DataSet>
  <xs:schema id=“Camera“ xmlns=“” xmlns:xs=“http://www.w3.org/2001/XMLSchema“ xmlns:msdata=“urn:schemas-microsoft-com:xml-msdata“>
    <xs:element name=“Camera“ msdata:IsDataSet=“true“ msdata:UseCurrentLocale=“true“>
      <xs:complexType>
        <xs:choice minOccurs=“0“ maxOccurs=“unbounded“>
          <xs:element name=“CameraDetails“>
            <xs:complexType>
              <xs:sequence>
                <xs:element name=“MakeModel“ type=“xs:string“ minOccurs=“0“ />
                <xs:element name=“Price“ type=“xs:string“ minOccurs=“0“ />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:msdata=“urn:schemas-microsoft-com:xml-msdata“ xmlns:diffgr=“urn:schemas-microsoft-com:xml-diffgram-v1“>
    <Camera>
      <CameraDetails diffgr:id=“CameraDetails1“ msdata:rowOrder=“0“ diffgr:hasChanges=“inserted“>
        <MakeModel>Canon EOS-1D</MakeModel>
        <Price>$ 5219</Price>
      </CameraDetails>
      <CameraDetails diffgr:id=“CameraDetails2“ msdata:rowOrder=“1“ diffgr:hasChanges=“inserted“>
        <MakeModel>Canon EOS-1D Mark IV</MakeModel>
        <Price>$ 5000</Price>
      </CameraDetails>
    </Camera>
  </diffgr:diffgram>
</DataSet>


In this article, we have learned c# object serialization using an XML serializer. I hope you enjoyed the article. If yes then please feel free to share the article on your favorite social media using below “Sharing is Caring” widget.



Do you know:-




If you like the tutorial, then please share this tutorial with your friends on social media.
Share it:

C#

Windows Forms

Post A Comment:

0 comments: