简体   繁体   中英

Cannot deserialize sub-elements to list of objects

I am having problems serializing elements of an XML to a list of objects.

This is the XML:

<result>
  <stats>
    <numitemsfound>1451</numitemsfound>
    <startfrom>0</startfrom>
  </stats>
  <items>
    <item>
      <id>1</id>
      <markedfordeletion>0</markedfordeletion>
      <thumbsrc>
      </thumbsrc>
      <thumbsrclarge>
      </thumbsrclarge>
      ...
      <datasource>65</datasource>
      <data>
        <amount>100</amount>
        <kj>389</kj>
        <kcal>92.91</kcal>
        <fat_gram>0.2</fat_gram>
        <fat_sat_gram>-1</fat_sat_gram>
        <kh_gram>20.03</kh_gram>
      </data>
      <servings>
        <serving>
          <serving_id>386</serving_id>
          <weight_gram>150</weight_gram>
        </serving>
      </servings>
    </item>
</result>

The classes I prepared for serialization are

 [XmlType("item")]
    public class Item
    {
        [XmlAttribute("id")]
        public string id { get; set; }
        [XmlAttribute("markedfordeletion")]
        public string markedfordeletion { get; set; }
        ...
        [XmlAttribute("datasource")]
        public string datasource { get; set; }

        [XmlElement("data")]
        public Data data { get; set; }

        [XmlElement("servings")]
        public List<Serving> servings { get; set; }
    }
}

This is how I try to serialize the xml

public void ParseSearch(string xml)
{
    XmlSerializer serializer = new XmlSerializer(typeof(List<Item>), new XmlRootAttribute("item"));
    StringReader stringReader = new StringReader(xml);
    var productList = (List<Item>)serializer.Deserialize(stringReader);
}

But I get the error ----> System.InvalidOperationException : <result xmlns=''> was not expected. Can you please help me solve this problem?

You have to use a serializer which serializes an instance of result , not of type List :

XmlSerializer serializer = new XmlSerializer(typeof(Result), new XmlRootAttribute("result"));  //whatever `Result` actually is as type).

You can´t serialize and de-serialize just parts of a document, either the whole one or nothing at all.

So you need a root-type:

[XmlRoot("result")]
public class Result
{
    public Stats Stats {get; set;}
    [XmlArray("items")]
    [XmlArrayItem("item")] 
    public List<Item> Items { get; set; }
}

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