Sunday, July 12, 2009

About XML Serialization.

[quote]

I want to know something about Serialization and XML Serialization.
[/quote]

Well in very simple and raw words if u want to convert any object(which implements the Isearilizabel intercface)
in to xml (string) u can use XML serilization.

That is if ur class is like this.


[Serializable]
public class tryMe
{
public tryMe() { }

private string _firstName = string.Empty;
private string _lastName = string.Empty;
public string firstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string lastName
{

get { return _lastName; }
set { _lastName = value; }
}
}


And when u serilize it.. it will give u output in xml format like this.

< tryMe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
< firstName >Kavita< /firstName >
< lastName >Khandhadia< /lastName >
< /tryMe >

Now if u want to serilize it then u can write code like this.

tryMe tm = new tryMe();
tm.firstName = "Kavita";
tm.lastName = "Khandhadia";

XmlElement xe = Serialize(tm);
string outStr = xe.OuterXml;

See the out put in the outStr Varibale.

Now u need the Serialize(tm) function which is like following.


public XmlElement Serialize(object transformObject)
{
XmlElement serializedElement = null;
try
{
MemoryStream memStream = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(transformObject.GetType());
serializer.Serialize(memStream, transformObject);
memStream.Position = 0;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(memStream);
serializedElement = xmlDoc.DocumentElement;
}
catch (Exception SerializeException)
{

}

Thats all about how to Use XMl serilize

1 comment:

  1. Prepare for IBM M2090-733 exam with our preparation material with full confidence. We offer you 100% real IBM SPSS Statistics Sales Mastery Test v1 IBM M2090-733 exam dumps for your better results. Prepare4Test’s M2090-733 pdf dumps are verified by IBM Gurus.

    ReplyDelete