反序列化XML - 如何反序列化嵌套列表?

时间:2015-06-17 14:38:57

标签: c# xml xml-deserialization

我正在尝试反序列化这个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>

我只对Specs列表感兴趣,但似乎无法反序列化它。我尝试过以下方法:

类:

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

并使用此方法进行反序列化,没有任何乐趣:

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

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

1 个答案:

答案 0 :(得分:0)

您在Model内以及Response内有规格。您的XML设置方式将进入Model

您还需要所有其他项目的属性。

从这样的事情开始

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

如果这不起作用,请创建一个对象并对其进行序列化,然后查看该XML与您要使用的XML之间的差异。