Name des XmlSerializer-Listenelementes
ich habe ein klassePersonList
[XmlRoot("Persons")]
PersonList : List<Human>
Wenn ich dies in XML serialisiere, wird standardmäßig Folgendes erzeugt:
<Persons>
<Human>...</Human>
<Human>...</Human>
</Persons>
Meine Frage ist, was getan werden muss, um das Element zu ändernHuman
zuPerson
in der Ausgabe? Die Ausgabe wäre also:
<Persons>
<Person>...</Person>
<Person>...</Person>
</Persons>
und wie man das obige XML in das deserialisiertPersonList
Klassenobjekt?
Per Nicks Rat, hier ist mein Testcode:
[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());
}
}
Die Ausgabe des Testcodes lautet:
<Persons>
<Human>
<Name>John</Name>
</Human>
<Human>
<Name>Peter</Name>
</Human>
</Persons>
Wie die Ausgabe zeigt, ist die[XmlRoot("Person")]
aufHuman
ändert das Tag nicht inPerson
vonHuman
.