Xml Serialization in Csharp


The code shows how to apply XML serialization attributes and their functionality of the classes or Entities. The code shows how these attributes format the XML generated by serialization and deserialization.

The code shows how to apply XML serialization attributes and their functionality o the classes or Entities. The code shows how these attributes format the XML generated by serialization.

This code contains a class named Person, which stores institute information and has some public fields and an array field, which contains objects of another class called PersonDetails. In the Main method, We create and initialize an object of Person and then serialize it to an XML file and Test.xml Finally, you deserialize it into another object of Institute.



public class Person
{

[XmlAttribute]
public string Name;
[XmlAnyAttribute]
public XmlAttribute[] xAttributes;
[XmlAnyElement]
public XmlElement[] XElement;
[XmlElement(ElementName = PersonDetails
public PersonDetails[] PersonDetails;
}
static void Main(string[] args)
{

string file = "Test.xml";

XmlSerializer XS = new XmlSerializer(typeof(Person));

TextWriter TW = new StreamWriter(file);

Person PS= new Person();

PS.Name = "ramu";
PersonDetails details = new PersonDetails();
details .Name = "Kailash";
details .ID = "S32";
details .RegisterNo = "R31";
PersonDetails details1 = new PersonDetails();
details1.Name = "Ramsharan";
details1.ID = "S33";
details1.RegisterNo = "R32";
PS.PersonDetails = new PersonDetails[2] { details, details };

XS.Serialize(TW, PS);
TW.Flush();
TW.Dispose();
TW.Close();
FileStream FS = new FileStream(file, FileMode.Open);
Person PS1= new (Person);XS.Deserialize(FS);
Console.WriteLine(PS1.Name);
Console.WriteLine("--------------------------------------");
Console.WriteLine("Persons List");
Console.WriteLine("------------");
foreach (PersonDetails st in PS1.PersonDetails)
{
Console.WriteLine(" ");
Console.WriteLine(st.Name);
Console.WriteLine(st.ID);
Console.WriteLine(st.RegisterNo);
}
Console.ReadLine();
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: