Problem in xml deserialization

Asked

Viewed 43 times

-1

I am trying to convert the following xml into object

inserir a descrição da imagem aqui

But it returns the empty categories

inserir a descrição da imagem aqui

Code:

Records records = new Records();
XmlSerializer serializer = new XmlSerializer(typeof(Records));
records = (Records)serializer.Deserialize(new StringReader(xmlReportCategoria));

Records:

public class Records
{
    public List<Categoria> Categoria { get; set; }
}

Category:

public class Categoria
{
    public int Cat_ID { get; set; }
    public string Cat_Nome { get; set; }
    public List<SubCategoria> SubCategoria { get; set; }
}

Subcategory:

public class SubCategoria
{
    public int CatRaiz_ID { get; set; }
    public int SubCat_ID { get; set; }
    public string SubCat_Nome { get; set; }
    public string SubCat_Keywords { get; set; }
}
  • and the mistake as it is?

  • No error, it just brings the list of categories Count = 0, added a new image showing this

1 answer

0

You need to specify in your class which element is the root of your list with the XmlRoot. The rest follow the way it is.

Behold:

    public class Records
    {
        [XmlElement("Categoria")]
        public Categoria[] Categorias { get; set; }
    }


    [XmlRoot("Records")]
    public class Categoria
    {

        public int Cat_ID { get; set; }

        public string Cat_Nome { get; set; }

        [XmlElement("SubCategoria")]
        public List<SubCategoria> SubCategorias { get; set; }
    }

    [XmlRoot("Categoria")]
    public class SubCategoria
    {
        public int CatRaiz_ID { get; set; }
        public int SubCat_ID { get; set; }
        public string SubCat_Nome { get; set; }
        public string SubCat_Keywords { get; set; }
    }
  • It worked that way, thank you!

  • From what you’re saying, it seems to be the case mark an answer as accepted. Here we do not write "solved" in the question. If you have an answer that really helped you, mark it as accepted. If you came to the solution on your own, put in the solution as an answer. So content is more organized and easier to find in the future by other people with similar problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.