tags:

views:

20

answers:

2

Can someone please help me? I'm trying to extract the PostalCode, Latitude and Longitude values from the XML below using LINQ. My efforts are resulting in a null IEnumerable ! The XML has been retuned from the BING REST server. I'm sure it's not hard, it's just my LINQ is poor. Thanks in advance

<?xml version="1.0"?>
<GeocodeFeed >
  <GeocodeEntity Id="1" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode"&gt;
    <GeocodeRequest Culture="en-GB" Query="RG6 1WG" />
<GeocodeEntity Id="1" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode"&gt;
    <GeocodeRequest Culture="en-GB" Query="RG6 1WG" />
    <GeocodeResponse DisplayName="RG6 1WG, Wokingham, United Kingdom" EntityType="Postcode1" Confidence="High" StatusCode="Success">
        <Address AdminDistrict="England" CountryRegion="United Kingdom" FormattedAddress="RG6 1WG, Wokingham, United Kingdom" PostalCode="RG6 1WG" />
        <RooftopLocation Latitude="51.461179330945" Longitude="-0.925943478941917" />
    </GeocodeResponse>
</GeocodeEntity></GeocodeFeed>
A: 

I'm assuming that if a GeocodeResponse has an Address element, it also has a RooftopLocation element.

XDocument document = XDocument.Load(<your feed>);
IEnumerable<XElement> responses = document.XPathSelectElement("//GeocodeEntity/GeocodeResponse[Address]");

foreach (XElement response in responses)
{
    string postalCode = response.Element("Address").Attribute("PostalCode").Value;
    string latitude = response.Element("RooftopLocation").Attribute("Latitude").Value;
    string longitude = response.Element("RooftopLocation").Attribute("Longitude").Value;
}

Hopefully, this should get you started where you want to go...

Neil T.
A: 

Thanks Neil.T: Your code didn't quite work, but gave me enough to go on, many thanks. Here's my 1st solution, I'm sure it can be refactored etc. Prior to using LINQ, I had some very nasty looking Regular expressions doing the work, thankfully they're a thing of the past in this solution.

        float latitude, longitude;
        string postalCode;
        XDocument loaded = XDocument.Load(url);
        IEnumerable<XNode> responses = loaded.DescendantNodes(); 
        foreach (XElement response in responses)
        {
            if (response.Name.LocalName.Equals("Address"))
            {
                postalCode = response.Attribute("PostalCode").Value;
            }
            if (response.Name.LocalName.Equals("RooftopLocation"))
            {
                latitude = float.Parse(response.Attribute("Latitude").Value);
                longitude = float.Parse(response.Attribute("Longitude").Value);
            }
        }     
Rory