如何反序列化具有多个属性的XML文档

时间:2018-12-23 03:41:21

标签: c# xml serialization

我正在尝试将一个xml文档反序列化为C#类

我遵循了该tuto,但在我的情况下却无效:https://stackoverflow.com/a/364401/10824921

但是我的列表人员仍然为空

有XML:

<?xml version="1.0" encoding="utf-8"?>
<PersonList>
  <Person id="0" tag="ASD">
    <Name>Smith</Name>
  </Person>
  <Person id="1" tag="FDS">
    <Name>Johny</Name>
  </Person>
</PersonList>

有C#代码:

[Serializable()]
[XmlRoot("PersonList")]
public class PersonList
{
    [XmlArrayItem("Person", typeof(Person))]
    public Person[] Person { get; set; }
}
[Serializable()]
public class Person
{
    [XmlAttribute("id")]
    public int ID { get; set; }
    [XmlAttribute("tag")]
    public string Tag{ get; set; }
    [XmlElement("Name")]
    public string Name{get; set;}

}

class Program
{
    static void Main(string[] args)
    {
        PersonList listPersons = null;
        string path = "personlist.xml";

        XmlSerializer serializer = new XmlSerializer(typeof(PersonList ));

        StreamReader reader = new StreamReader(path);
        listPersons= (PersonList)serializer.Deserialize(reader);
        reader.Close();
    }
}

1 个答案:

答案 0 :(得分:1)

将模型更改为:

[XmlRoot(ElementName = "PersonList")]
public class PersonList
{
    [XmlElement(ElementName = "Person")]
    public List<Person> Person { get; set; }
}

[XmlRoot(ElementName = "Person")]
public class Person
{
    [XmlElement(ElementName = "Name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "id")]
    public string Id { get; set; }
    [XmlAttribute(AttributeName = "tag")]
    public string Tag { get; set; }
}

问题是[XmlArrayItem("Person", typeof(Person))]

您可以使用此helpful tool将xml转换为C#类