简体   繁体   中英

Reading data from XML file in C#

I am attempting to read data from an XML file in C# (for Windows Phone). I return the following XML file:

private async void GetCoords2()
    {
        string requestURI = "https://maps.googleapis.com/maps/api/geocode/xml?address=Donegal%20Town&key=XXX";

        HttpWebRequest request = HttpWebRequest.Create(requestURI) as HttpWebRequest;
        WebResponse response = await request.GetResponseAsync();
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            responseContent = reader.ReadToEnd();
            // Do anything with you content. Convert it to xml, json or anything.

            ParseContent();
        }
    }

I am attempting to retrieve the first instance of latitude and longtitude from the XML file, which is available here: https://maps.googleapis.com/maps/api/geocode/xml?address=Donegal%20Town&key=XXX

I have followed several samples from online, and previous projects I have worked on, but none seem to be working.

How can I retrieve the first instance of lat and lon?

Thanks.

Edit: had to remove key from URL, posted screenshot of image instead.

UPDATE: The code I currently have.

void ParseContent()
    {
        XmlReader xmlReader = XmlReader.Create(responseContent);
        List<string> aTitle = new List<string>();

        // Add as many as attributes you have in your "stop" element

        XmlReader reader = XmlReader.Create(responseContent);
        reader.ReadToDescendant("location");
        while (reader.Read())
        {
            reader.MoveToFirstAttribute();

            reader.ReadToFollowing("lat");
            string latX = reader.ReadElementContentAsString();

            reader.ReadToFollowing("lng");
            string lngX = reader.ReadElementContentAsString();

            //reader.ReadToFollowing("Subcategory");
            //string subcategory = reader.ReadElementContentAsString();

            //reader.ReadToFollowing("Favourited");
            //Boolean favourited = Boolean.Parse(reader.ReadElementContentAsString());

            //basketxml.Add(new Pets(name, category, subcategory, description, dob, stock, price, image, id, favourited));

            MessageBox.Show(latX + " / " + lngX);
        }
    }

FOUND ANSWER HERE: http://www.superstarcoders.com/blogs/posts/geocoding-in-c-sharp-using-google-maps.aspx

Try something like this....

Usings...

using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

Classes.... .(created from your XML using http://xmltocsharp.azurewebsites.net/ )

    [XmlRoot(ElementName = "address_component")]
    public class Address_component
    {
        [XmlElement(ElementName = "long_name")]
        public string Long_name { get; set; }
        [XmlElement(ElementName = "short_name")]
        public string Short_name { get; set; }
        [XmlElement(ElementName = "type")]
        public List<string> Type { get; set; }
    }

    [XmlRoot(ElementName = "location")]
    public class Location
    {
        [XmlElement(ElementName = "lat")]
        public string Lat { get; set; }
        [XmlElement(ElementName = "lng")]
        public string Lng { get; set; }
    }

    [XmlRoot(ElementName = "southwest")]
    public class Southwest
    {
        [XmlElement(ElementName = "lat")]
        public string Lat { get; set; }
        [XmlElement(ElementName = "lng")]
        public string Lng { get; set; }
    }

    [XmlRoot(ElementName = "northeast")]
    public class Northeast
    {
        [XmlElement(ElementName = "lat")]
        public string Lat { get; set; }
        [XmlElement(ElementName = "lng")]
        public string Lng { get; set; }
    }

    [XmlRoot(ElementName = "viewport")]
    public class Viewport
    {
        [XmlElement(ElementName = "southwest")]
        public Southwest Southwest { get; set; }
        [XmlElement(ElementName = "northeast")]
        public Northeast Northeast { get; set; }
    }

    [XmlRoot(ElementName = "geometry")]
    public class Geometry
    {
        [XmlElement(ElementName = "location")]
        public Location Location { get; set; }
        [XmlElement(ElementName = "location_type")]
        public string Location_type { get; set; }
        [XmlElement(ElementName = "viewport")]
        public Viewport Viewport { get; set; }
        [XmlElement(ElementName = "bounds")]
        public Bounds Bounds { get; set; }
    }

    [XmlRoot(ElementName = "result")]
    public class Result
    {
        [XmlElement(ElementName = "type")]
        public List<string> Type { get; set; }
        [XmlElement(ElementName = "formatted_address")]
        public string Formatted_address { get; set; }
        [XmlElement(ElementName = "address_component")]
        public List<Address_component> Address_component { get; set; }
        [XmlElement(ElementName = "geometry")]
        public Geometry Geometry { get; set; }
        [XmlElement(ElementName = "place_id")]
        public string Place_id { get; set; }
    }

    [XmlRoot(ElementName = "bounds")]
    public class Bounds
    {
        [XmlElement(ElementName = "southwest")]
        public Southwest Southwest { get; set; }
        [XmlElement(ElementName = "northeast")]
        public Northeast Northeast { get; set; }
    }

    [XmlRoot(ElementName = "GeocodeResponse")]
    public class GeocodeResponse
    {
        [XmlElement(ElementName = "status")]
        public string Status { get; set; }
        [XmlElement(ElementName = "result")]
        public List<Result> Result { get; set; }
    }

Code...

        try
        {
            string query1 = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?address=Donegal%20Town&key=<Your Key>");
            XmlDocument GeocodeResponse = new XmlDocument();
            GeocodeResponse.Load(query1);

            string XMLGeocodeResponse = GeocodeResponse.InnerXml.ToString();
            byte[] BUFGeocodeResponse = ASCIIEncoding.UTF8.GetBytes(XMLGeocodeResponse);
            MemoryStream ms1 = new MemoryStream(BUFGeocodeResponse);

            XmlSerializer DeserializerPlaces = new XmlSerializer(typeof(GeocodeResponse), new XmlRootAttribute("GeocodeResponse"));
            using (XmlReader reader = new XmlTextReader(ms1))
            {
                GeocodeResponse dezerializedXML = (GeocodeResponse)DeserializerPlaces.Deserialize(reader);

                Location LatLng = dezerializedXML.Result[0].Geometry.Location;
            }// Put a break-point here, then mouse-over LatLng and you should have you values
        }
        catch (System.Exception)
        {
            throw;
        }

This will deserialize the whole thing into a single object, then you can select elements you need (as you can see with 'LatLng' above has the two coordinates you wanted to extract)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM