XML Serialization
Serialization is the process of taking the state of an object and persisting it in some fashion. The Microsoft .NET Framework includes powerful objects that can serialize any object to XML. The System.Xml.Serialization namespace provides this capability.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, click 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.
- Click Add. A new class is created.
Note In Visual Studio .NET , click Open. - Add the following code after the Public Class clsPerson statement
public string
FirstName;
public string
MiddleName;
public string
LastName;
- Switch to the code window for Program.cs in Visual Studio or for Class1.cs in Visual Studio .NET
- In the void Main method, declare and create an instance of the clsPerson class:
clsPerson
p = new clsPerson();
Set
the properties of the clsPerson object:
p.FirstName = "Naresh";
p.MiddleName = "Kumar";
p.LastName = "Kamuni";
- The Xml.Serialization namespace contains an XmlSerializer class that serializes an object to XML. When you create an instance of XmlSerializer, you pass the type of the class that you want to serialize into its constructor:
System.Xml.Serialization.XmlSerializer x =
new
System.Xml.Serialization.XmlSerializer(typeof(clsPerson));
- The Serialize method is used to serialize an object to XML. Serialize is overloaded and can send output to a TextWriter, Stream, or XMLWriter object. In this example,
- you send the output to the console:
x.Serialize(Console.Out,p);
Console.WriteLine();
Console.ReadLine();
To verify that your project works,
press CTRL+F5 to run the project.
A clsPerson object is
created and populated with the values that you entered.
This state is serialized to XML.
The console window shows the following:
<?xml version="1.0"
encoding="IBM437"?>
<clsPerson
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstName>Naresh</FirstName>
<MiddleName>Kumar</MiddleName>
<LastName>Kamuni</LastName>
</clsPerson>
(OR)
you send the output to the Stream:
System.IO.FileStream stream =
new
System.IO.FileStream("XMLFile1.xml", FileMode.Create);
x.Serialize(stream, p);
then your XMLFile.xml file is
created in your Debug folder
The following snopshot is shows
code about send the output to Stream:
0 comments:
Post a Comment