.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal

Home >> Forum >> .NET Framework >> Post New QuestionBookmark and Share Subscribe to Forum

XML Serialization Of List that contains List

Posted By: Sajid P K     Posted Date: October 15, 2010    Points:2   Category :.NET Framework
Please look at the sample class below,

public class People


public People()



string _name;

public string Name { get; set; }

int _age;

public int Age { get; set; }

List<People> _children;

public List<People> Children { get; set; }



Now I have a list of type people with data like List<People> peopleList; And I want to serialize the peopleList object to XML , Could you please tell me how could I do that?

If I pass the peopleList directly to serializer as a aparameter it's throwing InvalidCastOperation exception.

Author: Jean Paul             
Posted Date: October 18, 2010     Points: 5   

Dude.. You can serialize and deserialize using the following code.
(XmlSerialization is a good approach here)

// Create Object
People people = new People();
people.Name = "Parent";
people.Age = 30;
people.Children = new List<People>();
people.Children.Add(new People() { Age = 1, Name = "Child" });

// Serialize
XmlSerializer serializer = new XmlSerializer(typeof(People));
TextWriter textWriter = new StreamWriter(@"C:\people.xml");
serializer.Serialize(textWriter, people);

// Deserialize
XmlSerializer deserializer = new XmlSerializer(typeof(People));
TextReader textReader = new StreamReader(@"C:\people.xml");
People newPeople = (People)deserializer.Deserialize(textReader);

// Check
bool result = (people.Name == newPeople.Name) &&
(people.Children.Count == newPeople.Children.Count);

Please let me know any changes needed
Please mark as answered

Jean Paul http://jeanpaulva.com/

Post Reply

You must Sign In To post reply
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend