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

时间:2016-12-07 13:40:00

标签: c# xml serialization

我在将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>

我为序列化准备的课程是

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

这是我尝试序列化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);
}

但我收到错误----> System.InvalidOperationException : <result xmlns=''> was not expected.你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您必须使用序列化程序来序列化result的实例,而不是List类型的实例:

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

您无法对文档的某些部分进行序列化和反序列化,无论是整个文档还是什么都不进行。

所以你需要一个root-type:

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