Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c# - Deserializing into a List without a container element in XML

In all the examples I've seen of using XmlSerializer any time a list or array happens you have some sort of container element like this:

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

However, the XML I have has no container similar to Things above. It just starts repeating elements. (Incidentally, the XML is actually from Google's Geocode API)

So, I have XML that looks like this:

<?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>

As you can see inside result the type element repeats without any types element that XmlSerializer appears to expect (or at least all the documents and examples I've seen). The same goes for the address_component.

The code I currently have looks something like this:

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

Every time I attempt to deserialize the XML I get zero items in my Result List.

Can you suggest how I may get this to work as I'm currently not seeing it?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...