使用XElement将xml响应解析为Model类

时间:2011-07-06 15:42:54

标签: c# xml bing xelement

我有以下课程:

public class Location
{
    public string Name { get; set; }
    public long Latitude { get; set; }
    public long Longitude { get; set; }
    public string AddressLine { get; set; }
    public string FormattedAddress { get; set; }
    public string PostalCode { get; set; }


}

来自我的RESTful请求的以下XML响应:

<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
<BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
<StatusCode>200</StatusCode>
<StatusDescription>OK</StatusDescription>
<AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
<TraceId>xxx</TraceId>
<ResourceSets>
<ResourceSet>
  <EstimatedTotal>1</EstimatedTotal>
  <Resources>
    <Location>
      <Name>L4 0TH, Liverpool, Liverpool, United Kingdom</Name>
      <Point>
        <Latitude>53.431259840726852</Latitude>
        <Longitude>-2.9616093635559082</Longitude>
      </Point>
      <BoundingBox>
        <SouthLatitude>53.427397123156176</SouthLatitude>
        <WestLongitude>-2.9702530969854752</WestLongitude>
        <NorthLatitude>53.435122558297529</NorthLatitude>
        <EastLongitude>-2.9529656301263412</EastLongitude>
      </BoundingBox>
      <EntityType>Postcode1</EntityType>
      <Address>
        <AdminDistrict>England</AdminDistrict>
        <AdminDistrict2>Liverpool</AdminDistrict2>
        <CountryRegion>United Kingdom</CountryRegion>
        <FormattedAddress>L4 0TH, Liverpool, Liverpool, United Kingdom</FormattedAddress>
        <Locality>Liverpool</Locality>
        <PostalCode>L4 0TH</PostalCode>
      </Address>
      <Confidence>High</Confidence>
    </Location>
  </Resources>
</ResourceSet>

如何将Name,Latitude,Longitude,AddressLine,FormattedAddress和PostalCode的值输入我的属性?

我的方法是:

internal Location ListLocations()
    {
        Location loc = new Location();
        string query = "L40TH";
        string key = "MyBingMapsKey";
        string url = string.Format("http://dev.virtualearth.net/REST/v1/Locations/{0}?o=xml&key={1}", query, key);
        XElement elements = GetResponse(url);

        // stuck here!

    }

2 个答案:

答案 0 :(得分:4)

我会这样做:

static readonly XNamespace Ns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

static Location LocationFromXml(XElement element)
{
    var point = element.Element(Ns + "Point");
    return new Location
    {
        Name = (string)element.Element(Ns + "Name"),
        Latitude = (long)(float)point.Element(Ns + "Latitude"), // probably not exactly what you want
        Longitude = (long)(float)point.Element(Ns + "Longitude"),
        AddressLine = null, // not sure what do you want here
        FormattedAddress = null, // ditto
        PostalCode = (string)element.Element(Ns + "Address").Element(Ns + "PostalCode")
    };
}

然后在ListLocations()

var location = elements.Element(Ns + "ResourceSets")
                       .Element(Ns + "ResourceSet")
                       .Element(Ns + "Resources")
                       .Element(Ns + "Location");
return LocationFromXml(location);

答案 1 :(得分:0)

您可以使用XPath轻松获取正确的数据并手动填写位置属性(甚至更好,将代码添加到Location类)。关键是Linq to XML的XPath extension methods。特别要注意XPathSelectElementXPathEvaluate

loc.Name = elements.XPathSelectElement("//Name").Value;
loc.Latitude = Convert.ToInt64(elements.XPathSelectElement("//Latitude").Value);
loc.Longitude = Convert.ToInt64(elements.XPathSelectElement("//Longitude").Value);
//loc.AddressLine = ??? (Not sure what the intended value is here...)
loc.FormattedAddress = elements.XPathSelectElement("//FormattedAddress").Value;
loc.PostalCode = elements.XPathSelectElement("//PostalCode").Value;