在XML中反序列化为没有容器元素的List

Col*_*kay 56 .net c# xml-serialization

在我看到的所有示例中,XmlSerializer无论何时使用列表或数组,您都会遇到某种类似容器的元素:

<MyXml>
  <Things>
    <Thing>One</Thing>  
    <Thing>Two</Thing>  
    <Thing>Three</Thing>  
  </Things>
</MyXml>
Run Code Online (Sandbox Code Playgroud)

但是,我所拥有的XML没有类似上面的东西的容器.它只是开始重复元素.(顺便提一下,XML实际上来自Google的Geocode API)

所以,我有这样的XML:

<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
  <status>OK</status>
  <result>
    <type>locality</type>
    <type>political</type>
    <formatted_address>Glasgow, City of Glasgow, UK</formatted_address>
    <address_component>
      <long_name>Glasgow</long_name>
      <short_name>Glasgow</short_name>
      <type>locality</type>
      <type>political</type>
    </address_component>
    <address_component>
      <long_name>East Dunbartonshire</long_name>
      <short_name>East Dunbartonshire</short_name>
      <type>administrative_area_level_3</type>
      <type>political</type>
    </address_component>
    <!-- etc... -->
  </result>
  <result>
    <!-- etc... -->
  </result>
  <result>
    <!-- etc... -->
  </result>
</GeocodeResponse>
Run Code Online (Sandbox Code Playgroud)

正如你可以看到里面的结果,类型元素重复没有XmlSerializer所期望的任何类型元素(或至少我见过的所有文档和示例)._address_component_也是如此.

我目前的代码看起来像这样:

[XmlRoot("GeocodeResponse")]
public class GeocodeResponse
{
    public GeocodeResponse()
    {
        this.Results = new List<Result>();
    }

    [XmlElement("status")]
    public string Status { get; set; }

    [XmlArray("result")]
    [XmlArrayItem("result", typeof(Result))]
    public List<Result> Results { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

每次我尝试反序列化XML时,我在Result _List_中得到零项.

你可以建议我如何让这个工作,因为我目前没有看到它?

Ali*_*tad 90

使用

[XmlElement("result")]
public List<Result> Results { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • 它奏效了 - 我无法相信我错过了那么愚蠢的简单.卫生署! (3认同)