How to Serialize a List<>

M

Microsoft

I want to serialize a List<>. When I do I get an entry for each object in
the list but not the object's state.

My code:
//Person is a simple class that has fields for first and last name
List<Person> persons = new List<Person>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
persons.Add(new Person("Joe", "Tester"));
persons.Add(new Person("Mary", "Tetser"));
serializer.Serialize(Console.Out, persons);

And I get...
<?xml version="1.0" encoding="IBM437"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="
http://www.w3.org/2001/XMLSchema">
<Person />
<Person />
</ArrayOfPerson>

Thank you for any help!
 
M

Microsoft

I realize looking at your code that serialization only takes place for
public memebers. I had first and last as private fields so that is why they
did not get serialized. I added a getter/setter for them and the
serialzation works corerctly now.
Thank you!


Tom John said:
Hi

I am guessing there is something not right with your person class. I've
taken your code and created my own person class and it works as expected:

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{

//Person is a simple class that has fields for first and last
name
List<Person> persons = new List<Person>();
XmlSerializer serializer = new
XmlSerializer(typeof(List<Person>));
persons.Add(new Person("Joe", "Tester"));
persons.Add(new Person("Mary", "Tetser"));
serializer.Serialize(Console.Out, persons);

}
}

public class Person
{
public Person() { }

public Person(string name, string role)
{
Name = name;
Role = Role;
}

private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}

private string _role;
public string Role
{
get { return _role; }
set { _role = value; }
}

}
}

Hope this helps

Tom

Microsoft said:
I want to serialize a List<>. When I do I get an entry for each object in
the list but not the object's state.

My code:
//Person is a simple class that has fields for first and last name
List<Person> persons = new List<Person>();
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
persons.Add(new Person("Joe", "Tester"));
persons.Add(new Person("Mary", "Tetser"));
serializer.Serialize(Console.Out, persons);

And I get...
<?xml version="1.0" encoding="IBM437"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="
http://www.w3.org/2001/XMLSchema">
<Person />
<Person />
</ArrayOfPerson>

Thank you for any help!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top