将带有XElement的xml响应解析到Model类中

本文关键字:Model 类中 响应 xml XElement | 更新日期: 2023-09-27 18:01:15

我有以下类:

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!
    }

将带有XElement的xml响应解析到Model类中

我会这样做:

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);

您可能可以使用XPath轻松获取正确的数据并手动填写Location属性(或者更好的做法是,将代码添加到Location类中(。关键是Linq到XML的XPath扩展方法。特别关注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;