Deserialize XML - how do I deserialize nested lists?

501 views Asked by At

I am trying to deserialize this XML:

<Response>
<Make Name="Audi">
<Model Name="A7">
<Specs>
<Spec Identifier="330025">...</Spec>
<Spec Identifier="330026">...</Spec>
<Spec Identifier="330027">...</Spec>
<Spec Identifier="330028">...</Spec>
<Spec Identifier="330008">...</Spec>
<Spec Identifier="330038">...</Spec>
<Spec Identifier="330024">...</Spec>
<Spec Identifier="330019">...</Spec>
<Spec Identifier="330020">...</Spec>

I'm only interested in the Specs list but can't seem to deserialize it. I have tried the following:

CLass:

  [XmlRoot]
    public class Response
    {
        [XmlArray("Specs"), XmlArrayItem("Spec")]
        public List<Spec> Results { get; set; }

        //[XmlArray("Specs"), XmlArrayItem("Spec")]
        public List<Make> Make { get; set; } 
    }


    public class Spec
    {
        [XmlAttribute("YearProductionStarts")]
        public string YearProductionStarts { get; set; }
        [XmlAttribute("YearProductionEnd")]
        public string YearProductionEnd { get; set; }
    }

    public class Make
    {
        public List<Model> Model { get; set; }
    }

    public class Model
    {
        public List<Spec> Spec { get; set; }
    }

and used this method to deserialize with no joy:

 //Deserialize responseXml to response object
            var xmLserializer = new XmlSerializer(typeof(ResponseGetSpec));

            using (var reader = new StringReader(responseXml))
            {
                return (ResponseGetSpec)xmLserializer.Deserialize(reader);
            }
1

There are 1 answers

0
Kyle W On

You have specs inside Model and also inside Response. The way your XML is set up it will go inside Model.

You also need attributes on all your other items.

Start with something like this

[XmlRoot]
public class Response
{
    [XmlElement("Make")] // Use XmlElement to get multiple items without a containing XML tag
    public List<Make> Make { get; set; } 
}


public class Spec
{
    [XmlAttribute("YearProductionStarts")]
    public string YearProductionStarts { get; set; }
    [XmlAttribute("YearProductionEnd")]
    public string YearProductionEnd { get; set; }
}

public class Make
{
    [XmlElement("Model")]
    public List<Model> Model { get; set; }
}

public class Model
{
    [XmlArray("Specs"), XmlArrayItem("Spec")]
    public List<Spec> Spec { get; set; }
}

If that doesn't work, create an object and serialize it, then see where the differences are between that XML and the XML you're going for.