XmlSerializer List Item Element Name

Qstonr picture Qstonr · Feb 18, 2010 · Viewed 68.2k times · Source

I have a class PersonList

[XmlRoot("Persons")]
PersonList : List<Human>

when I serialize this to XML, by default it will produce something like this:

<Persons>
  <Human>...</Human>
  <Human>...</Human>
</Persons>

My question is what needs to be done in order to change element Human to Person in the output? so the output would be :

<Persons>
  <Person>...</Person>
  <Person>...</Person>
</Persons>

and, how to deserialize the above XML to the PersonList class object?

Per Nick's advice, Here is my testing code:

[XmlRoot("Persons")]
public class Persons : List<Human>
{

}

[XmlRoot("Person")]
public class Human
{
    public Human()
    {
    }

    public Human(string name)
    {
        Name = name;
    }

    [XmlElement("Name")]
    public string Name { get; set; }

}

void TestXmlSerialize()
{
    Persons personList = new Persons();
    personList.Add(new Human("John"));
    personList.Add(new Human("Peter"));

    try
    {
        using (StringWriter writer = new StringWriter())
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Persons));
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;

            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            namespaces.Add(string.Empty, string.Empty);

            XmlWriter xmlWriter = XmlWriter.Create(writer, settings);
            serializer.Serialize(xmlWriter, personList, namespaces);

            Console.Out.WriteLine(writer.ToString());
        }
    }
    catch (Exception e)
    {
        Console.Out.WriteLine( e.ToString());
    }
}

The output of the testing code is:

<Persons>
  <Human>
    <Name>John</Name>
  </Human>
  <Human>
    <Name>Peter</Name>
  </Human>
</Persons>

As the output shows, the [XmlRoot("Person")] on Human does not change the tag to Person from Human.

Answer

tribe84 picture tribe84 · Oct 18, 2011

Mark your class with the following attributes:

[XmlType("Account")]
[XmlRoot("Account")]

The XmlType attribute will result in the output requested in the OP. Per the documentation:

Controls the XML schema that is generated when the attribute target is serialized by the XmlSerializer