The.NET framework contains many classes to help with this process, and offers in-built support for XML serialization (serializing an object to an XML data file) through the XmlSerializer class and the System.Xml.Serialization library. This article provides a brief overview of XML serialization and deserialization in the C# programming language. Controlling XML Serialization Using Attributes.; 6 minutes to read +2; In this article. Attributes can be used to control the XML serialization of an object or to create an alternate XML stream from the same set of classes. Serializing/Deserializing XML Attribute Lists. I've gotten so used to working with JSON that I'd almost forgotten what a chore it can be to work with XML.
- C Xml Serialization Attribute In Excel
- C# Xmlserializer
- C# Xml Serialization
- C# Xml Serialization Example
- C Xml Serialization Attribute Chart
- C# Xml Deserialization
Introduction
My previous article XML Serialization and Deserialization (Part-1) talks about serialization of objects to XML form. In this article, we will discuss about 'Deserialization of XML' back to object form. Deserialization is used to convert bytes of data, such as XML or binary data, to 'Object
' type. An XML file can be reconverted back to an Object using deserialization.
Let's start with the basic example. Here is the XML file that need to be deserialized:
So in order to deserialize this XML file, we need to create a class:
This class contains a variable name which is the same as that of XML tags, XML tag values by default get mapped to the corresponding variable in the class. 'HouseNo
' in class 'Address
' will be automatically mapped to XML tag 'HouseNo
'.
Now let's see a basic program which will map this XML to the class object:
'deserializer.Deserialize
' function is used to deserialize the XML data which is there in XML file. Now since we have deserialized the XML file structure to object form, we can now access the XML tag values:
The following points should be noted while creating a class for Deserialization:
- Class variable/property should always be declared as
public
- We need to have Default/ Non Parameterised constructor in order to deserialize
Any class without 'Default/ Non Parameterised' constructor will result into an error since 'deserializer.Deserialize(reader)
' has no provision to pass value to parameterised constructor.
In the above code, we have simple XML Elements present with no sub Elements. Let's explore further and deal with some complicated situations where the XML Element may have further sub Tags:
Let's complicate the situation further and try to 'deserialize' the following 'XML':
Let's see the difference over here. In the following XML, we have multiple 'Address
' tags. And also the Address
tag contains further sub Tags. Therefore, we need to create our class such that it can hold multiple 'Address
' tags and its sub tags. Let's see how we can create the class:
Remember here that when we create a class for deserialization of any tag, We can only drill down to a single level. To explain this in simple words, let me take an example. In the above XML, we have 'AddressDirectory
' tab. In order to Deserialize, we create a class for 'AddressDirectory
' tag. Now this class can have the details of following for 'AddressDirectory
' XML tag:
- Attribute of '
AddressDirectory
' tag if present - Its Childnodes example '
Address
' (can only access 'Address
tags', cannot drill down to child nodes of 'Address
' Tag) InnerText
(if present)
The class AddressDirectory
cannot extract information about the child tags of 'Address
' and the 'Address
' tag attributes. In order to fetch information about the 'ChildNodes
' of 'Address
' tag, we need to create another class that can store the attribute information and childnode
information (up to first level).
Over here, we have created a class AddressDirectory
that maps to the root tag element of 'XML'. And the root tag further contains 'Address
' tags. We can have multiple tags for 'Address
' over here, therefore we have created a list of class 'Address
' in 'AddressDirectory
' class so that multiple 'Address
' tag information can be stored. Here, in the class, we can see XmlElement
written over addressList
. This attribute is used since the name of the class variable is different from that in XML file therefore in order to map the class variable with the XML tag, we use the keyword XmlElement
. We will discuss about this later in the article.
We will see more examples about this further in the article.
The program to be executed in order to deserialize the XML will be:
The resultant object 'XmlData
' will contain a list of object of type 'Address
'. We can access the data for the first Address
tag as:
The XML can be further complicated, let's see the following XML file structure and its class representation:
Here, we can see some additional tags inside the 'AddressDirectory
' like 'Owner
', 'Age
', 'Company
' along with the list of 'Address
' tags. So the class structure for the XML would be:
The childnodes of 'AddressDirectory
' tags are present inside the AddressDirectory
class and the childnode
s of Address
tab are present inside the address
class.
Note: What is important to observe here is that the class can contain only those 'tag values' which are their immediate childnodes, i.e., AddressDirectory
can only contain the information about their immediate childnode like 'Owner
', 'Company
', 'Age
' and 'Address
'. But here, 'Address
' is further containing more tags. The childnodes for 'Address
' tag cannot be represented by the class 'AddresssDirectory
'. Therefore, we require another class for 'Address
' tag that stores the childnode
information about 'Address
' class. The 'Address
' class will further contain the value of their immediate childnode
'HouseNo
', 'StreetName
', 'City
'. Since we have multiple Address
tags, therefore we have a 'List
' of 'Address
' class.
XML Attributes during Deserialization
Attributes that can be useful during deserialization are:
XmlElement
XmlAttribute
XmlText
These three attributes provide mapping information. It provides information about which element of the XML tag will be mapped to which variable of the class.
Observe the following XML:
Let's observe the different components of this XML file:
AddressDirectory
is the root node of the XML fileAddressDirectory
contains an 'XmlAttribute
' as 'id
' containing value '1
'- '
AddressDirectory
' contains 'XmlElement
' likeDirectoryOwner
,Address
,Designation
,Address
- '
Designation
' tab contains an a 'XmlAttribute
' ('place
') and an 'XmlText
' ('Delhi
')
So from the above XML, we can figure out what are 'XmlElement
', 'XmlAttribute
', 'XmlText
'. While deserializing such complex XML where we can have all the three components, we need to explicitly specify whether the class variable stores 'Element
', 'Attribute
' or 'XmlText
'.
Let's try to desterilize this XML:
Here, we have mapped the class variable DirectoryOwner
to DirectoryOwner
tag of XML file.
Observe here that the class AddressDirectory
contains the child node of the AddressAttribute
tag. It drills down to the first level only, i.e., it cannot retrieve values about the Attribute
of Designation
and neither can it fetch information about the childnodes of Address
tag. Therefore, in order to extract these information, we need to create another class for Address
and Designation
. Since we have multiple Address
tags, we have a list of Address
class in AddressDirectory
.
Let's explore the Address
class and the Designation
class:
The Designation
class here contains two variables, one for storing the innerText
and other for storing the place
attribute for the Designation
tags.
The Address
class further contains a variable that can store the attributes and child node details of Address
tags.
The program to be executed in order to deserialize the XML will be:
One more thing that needs to be kept in mind is that, the keywords XmlElement
, XmlAttribute
, and XmlText
are used to map information inside the XML tag to the class variable. The class variable name can be different from that in XML. For example:
Here, we can see that the XML element HouseNo
will be mapped to the class variable Number
.
Conclusion
Deserialization and serialization is a very efficient way to convert the object to XML and vice versa. This save lots of saving time and effort.
I found out that some classes use the [Serializable]
attribute.
- What is it?
- When should I use it?
- What kinds of benefits will I get?
6 Answers
What is it?
When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.
Uses for Serialization
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
Apply SerializableAttribute
to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute
even if the class also implements the ISerializable
interface to control the serialization process.
All the public and private fields in a type that are marked by the SerializableAttribute
are serialized by default, unless the type implements the ISerializable
interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute
. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute
to that field.
See MSDN for more details.
Edit 1
Any reason to not mark something as serializable
When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.
CharithJCharithJSome practical uses for the [Serializable]
attribute:
C Xml Serialization Attribute In Excel
- Saving object state using binary serialisation; you can very easily 'save' entire object instances in your application to a file or network stream and then recreate them by deserialising - check out the
BinaryFormatter
class in System.Runtime.Serialization.Formatters.Binary - Writing classes whose object instances can be stored on the clipboard using
Clipboard.SetData()
- nonserialisable classes cannot be placed on the clipboard. - Writing classes which are compatible with .NET Remoting; generally, any class instance you pass between application domains (except those which extend from
MarshalByRefObject
) must be serialisable.
These are the most common usage cases that I have come across.
Bradley SmithBradley SmithSince the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.
C# Xmlserializer
It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.
It has NOTHING to do with XML or JSON serialization.
Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.
Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.
Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file.
How Serialization Works
This illustration shows the overall process of serialization.
The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.
Mahbubur RahmanMahbubur RahmanC# Xml Serialization
Here is short example of how serialization works. I was also learning about the same and I found two links useful.What Serialization is and how it can be done in .NET.
If you don't understand the above program a much simple program with explanation is given here.
StackedC# Xml Serialization Example
Serialization
Serialization is the process of converting an object or a set of objects graph into a stream, it is a byte array in the case of binary serialization
Uses of Serialization
- To save the state of an object into a file, database etc. and use it latter.
- To send an object from one process to another (App Domain) on the same machine and also send it over wire to a process running on another machine.
- To create a clone of the original object as a backup while working on the main object.
- A set of objects can easily be copied to the system's clipboard and then pasted into the same or another application
Below are some useful custom attributes that are used during serialization of an object
[Serializable] -> It is used when we mark an object's serializable[NonSerialized] -> It is used when we do not want to serialize an object's field.[OnSerializing] -> It is used when we want to perform some action while serializing an object[OnSerialized] -> It is used when we want to perform some action after serialized an object into stream.
Below is the example of serialization
Here is the calling code