XmlSerializer:指定序列化集合的名称

时间:2018-08-23 10:45:23

标签: c# xml xmlserializer

我有一个Person类,例如:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

我有一个Person序列,我想将它们序列化为XML格式。我不在乎是列表还是数组还是...

IEnumerable<Person> persons = 
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Person>));
using (TextWriter textWriter = new StringWriter())
{
    xmlSerializer.Serialize(textWriter, persons.ToArray());
    string xmlText = textWriter.ToString();
}

创建的xmlText类似于:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <Id>0</Id>
    <Name>Person 0</Name>
    <Birthday>2000-01-01T00:00:00</Birthday>
  </Person>

  <Person>
    <Id>1</Id>
    <Name>Person 1</Name>
    <Birthday>2000-02-02T00:00:00</Birthday>
  </Person>

  <Person>
    ...
  </Person>
  ...
</ArrayOfPerson>

我不喜欢<ArrayOfPerson>,我更喜欢<Persons>。该怎么做?

0 个答案:

没有答案