从C#中读取XML文件中的数据

时间:2016-03-24 19:43:45

标签: c# xml

我正在尝试从C#中的XML文件中读取数据(对于Windows Phone)。 我返回以下XML文件:

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

我正在尝试从XML文件中检索纬度和经度的第一个实例,可在此处获取:https://maps.googleapis.com/maps/api/geocode/xml?address=Donegal%20Town&key=XXX

我已经跟踪了几个在线样本,以及之前的项目,但似乎都没有。

如何检索lat和lon的第一个实例?

感谢。

编辑:不得不从网址中删除密钥,而是发布图片的截图。

更新:我目前拥有的代码。

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

在这里找到答案: http://www.superstarcoders.com/blogs/posts/geocoding-in-c-sharp-using-google-maps.aspx

1 个答案:

答案 0 :(得分:0)

尝试这样的事情......

... Usings

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

Classes ....(使用http://xmltocsharp.azurewebsites.net/从您的XML创建)

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

...代码

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

这会将整个事物反序列化为单个对象,然后您可以选择所需的元素(正如您在上面的'LatLng'中看到的那样,您有两个想要提取的坐标)...