简体   繁体   English

无法反序列化子元素到对象列表

[英]Cannot deserialize sub-elements to list of objects

I am having problems serializing elements of an XML to a list of objects. 我在将XML元素序列化为对象列表时遇到问题。

This is the XML: 这是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 这就是我尝试序列化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. 但是我收到了错误----> 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 : 您必须使用序列化程序来序列化result实例, result不是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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM