XML Serialization of custom collections

Say you have a class Person with the following members:
class Person
{
public string FirstName;
public string LastName;
public string SSNumber;
}

and a custom collection (not sure if this code works, it's just to give you an idea of what I'm doing)
class PeopleCollection
{
private Hashtable m_peopleBySS; // Person hashed by ssNumber
public Person[] People
{
get
{
ArrayList people = new ArrayList();
foreach(Person p in m_peopleBySS.Values)
{
people.Add(p);
}
return (Person[])people.ToArray(typeof(Person));
}
set
{
m_peopleBySS.Clear();
foreach(Person p in value)
{
m_peopleBySS[p.SSNumber] = p;
}
}
}
}

and finally a class which holds a group of people
class ClassRoom
{
public PeopleCollection Students;
}

When I serialize this collection to XML I'd like the following:
<ClassRoom>
<Students>
<Person>
<FirstName>Bob</FirstName>
<LastName>BobLast</FirstName>
<SSNumber>123456789</SSNumber>
</Person>
<Person>
<FirstName>Mary</FirstName>
<LastName>MaryLast</LastName>
<SSNumber>123456781</SSNumber>
</Person>
</Students>

I've tried implementing IEnumerable on my collection class, but then the XML looks like this:
<ClassRoom>
<Students>
<anyType xsi:type="Person">
<Person>
<FirstName>Bob</FirstName>
<LastName>BobLast</FirstName>
<SSNumber>123456789</SSNumber>
</Person>
<Person>
<FirstName>Mary</FirstName>
<LastName>MaryLast</LastName>
<SSNumber>123456781</SSNumber>
</Person>
</Students>
</ClassRoom>

I



Answer this question

XML Serialization of custom collections

  • XML Serialization of custom collections