0

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();
    }
}
  • 1
    Can you describe more about what doesn't work? At a glance, it looks OK. – Crowcoder Dec 23 '18 at 03:46
  • "... It doesn't work in my case..." - this information is not really helpful. It does not say what exactly did not work, i.e. did you get any error messages anywhere, did you try to debug the issue to make sure that it actually does the intended thing. – jazb Dec 23 '18 at 04:21

1 Answers1

1

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

M.Armoun
  • 1,075
  • 3
  • 12
  • 38