简体   繁体   中英

How to Deserialize XML document with multiple attribute

I'm trying to deserialize one xml document to c# class

I followed that tuto but It doesn't work in my case : https://stackoverflow.com/a/364401/10824921

But my listPersons remain empty

There is 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>

There is C# code :

[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();
    }
}

Change your model to :

[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; }
}

The problem is [XmlArrayItem("Person", typeof(Person))]

You can use this helpful tool to convert xml to C# Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM