【发布时间】:2011-03-11 09:58:26
【问题描述】:
在我见过的所有使用XmlSerializer 的示例中,每当列表或数组发生时,您都会有某种容器元素,如下所示:
<MyXml>
<Things>
<Thing>One</Thing>
<Thing>Two</Thing>
<Thing>Three</Thing>
</Things>
</MyXml>
但是,我拥有的 XML 没有类似于上面的 Things 的容器。它只是开始重复元素。 (顺便说一句,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>
正如您在 result 中看到的那样,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 时,我的 Result List 中的项目为零。
您能否建议我如何让它工作,因为我目前没有看到它?
【问题讨论】:
-
仅供参考:这个确切的问题已于昨天发布给 SO。 stackoverflow.com/questions/5259911/… 在 xml-serialization 标签下,在那个和这个之间有一个中间的 Q。此外,这不是第一次被询问/回答。
-
好吧,我找不到!我先搜索,然后在输入问题标题时单击所有建议。
标签: c# .net xml-serialization