XML Serialization sample

Madhu.B.Rokkam
Posted by Madhu.B.Rokkam under C# category on | Points: 40 | Views : 1227
Sample code to serialize objects using c#



using System;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp
{
public class XMLSerializationSample
{
public static void Main()
{
Student stu = new Student
{
Id = 10,
StudentName = "xyz",
Dob = Convert.ToDateTime("10/10/1979")
};
string resultWithXmlDeclarations = GetSerializedType(stu, typeof(Student), false);
Console.Write(resultWithXmlDeclarations);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
string resultWithOutXmlDeclarations = GetSerializedType(stu, typeof(Student), true);
Console.Write(resultWithOutXmlDeclarations);
Console.Read();
}

public static string GetSerializedType(Object o, System.Type type, bool removeXmlDeclarations)
{
System.Xml.Serialization.XmlSerializer serializer;
System.IO.StringWriter writer;
serializer = new System.Xml.Serialization.XmlSerializer(type);
writer = new System.IO.StringWriter();
serializer.Serialize(writer, o);

if (removeXmlDeclarations)
{
XmlDataDocument requestXmlDoc = new XmlDataDocument();
requestXmlDoc.LoadXml(writer.ToString());
//Remove <xml> element
requestXmlDoc.RemoveChild(requestXmlDoc.FirstChild);
//remove additional attributes
requestXmlDoc.DocumentElement.RemoveAttribute("xmlns:xsd");
requestXmlDoc.DocumentElement.RemoveAttribute("xmlns:xsi");
return requestXmlDoc.OuterXml;
}
return writer.ToString();
}
}

[Serializable]
public class Student
{
[XmlElement("StudentId")]
public int Id
{
get;
set;
}

public string StudentName
{
get;
set;
}

public DateTime Dob
{
get;
set;
}
}
}

Comments or Responses

Login to post response