Разобрать xml-ответ с помощью XElement в класс Model - PullRequest
0 голосов
/ 06 июля 2011

У меня есть следующий класс:

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


}

И следующий XML-ответ на мой запрос RESTful:

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

Как получить значениеИмя, Широта, Долгота, 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 ]

4 голосов
/ 06 июля 2011

Я бы сделал это так:

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);
0 голосов
/ 06 июля 2011

Вы, вероятно, можете использовать XPath, чтобы легко получить нужные данные и вручную заполнить свойства Location (или, что еще лучше, добавить код в класс Location). Ключ - методы расширения XPath для Linq to XML. Особенно посмотрите на XPathSelectElement и XPathEvaluate:

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