繁体   English   中英

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

[英]Deserializing into a List without a container element in XML

在我见过的所有使用XmlSerializer的示例中,任何时候列表或数组发生时,您都有某种容器元素,如下所示:

<MyXml>
  <Things>
    <Thing>One</Thing>  
    <Thing>Two</Thing>  
    <Thing>Three</Thing>  
  </Things>
</MyXml>

但是,我拥有的 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>

正如您在结果中看到的, type元素重复出现,没有XmlSerializer似乎期望的任何types元素(或至少我见过的所有文档和示例)。 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; }
}

每次我尝试反序列化 XML 时,我的结果列表中都会得到零个项目。

你能建议我如何让它工作,因为我目前没有看到它吗?

[XmlElement("result")]
public List<Result> Results { get; set; }

暂无
暂无

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

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