Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Serialization in C#

Where Can I find good tutorial about XMl serialization to the object? Thanks.

like image 994
jitm Avatar asked Jul 07 '10 14:07

jitm


People also ask

What is XML serialization?

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.

How do you serialize an object in XML?

Follow these steps to create a console application that creates an object, and then serializes its state to XML: In Visual C#, create a new Console Application project. On the Project menu, select Add Class to add a new class to the project. In the Add New Item dialog box, change the name of the class to clsPerson.

Is XML serializable?

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.

What is XML serialization and deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.


2 Answers

Its really pretty simple, there are only three main steps.

  1. You need to mark your classes with the [Serializable] attribute.
  2. Write Serialization code
  3. Write Deserialization code

Serialization:

var x = new XmlSerializer(typeof(YourClass));
var fs = new FileStream(@"C:\YourFile.xml"), FileMode.OpenOrCreate);
x.Serialize(fs, yourInstance);
fs.Close();

Deserialization:

var x = new XmlSerializer(typeof(YourClass));
var fs = new FileStream(@"C:\YourFile.xml"), FileMode.Open);
var fromFile = x.Deserialize(fs) as YourClass;
fs.Close();
like image 184
Nate Avatar answered Oct 07 '22 22:10

Nate


There's a basic tutorial on Microsoft's support pages and their code example is only a few lines long:

using System;

public class clsPerson
{
  public  string FirstName;
  public  string MI;
  public  string LastName;
}

class class1
{ 
   static void Main(string[] args)
   {
      clsPerson p=new clsPerson();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(Console.Out, p);
      Console.WriteLine();
      Console.ReadLine();
   }
}

Basically you don't have to anything other than call the built in functions that do all the hard work for you.

like image 39
ChrisF Avatar answered Oct 07 '22 23:10

ChrisF