c#獲取中國三級行政區域劃分(省市縣)以及縣級經緯度demo

1 定義三級model

   [XmlRoot("country")]
    public class Country
    {
        [XmlElement("provinces")]
        public List<Province> provinces { get; set; }
        [XmlAttribute]
        public string name { get; set; }
    }

 public class Province
    {
        [XmlElement("city")]
        public List<City> citys { get; set; }
        [XmlAttribute]
        public string name { get; set; }
        [XmlAttribute]
        public string code { get; set; }
    }


   public class City
    {
        [XmlElement("county")]
        public List<County> Counties { get; set; }
        [XmlAttribute]
        public string name { get; set; }
        [XmlAttribute]
        public string code { get; set; }
    }
   public class County
    {
        [XmlAttribute]
        public string name { get; set; }
        [XmlAttribute]
        public string code { get; set; }
        /// <summary>
        /// 經度
        /// </summary>
        [XmlAttribute]
    public double longitude { get; set; }
        /// <summary>
        /// 維度
        /// </summary>
        [XmlAttribute]
   public double latitude { get; set; }
    }

2 在線獲取行政區域劃分

地址:http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201504/t20150415_712722.html
獲取以上html代碼並解析出行政區域

string url = "http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201504/t20150415_712722.html";     string html = CoordinateHelper.HttpHelper(url);
string str = Regex.Match(html, "<div class=\"xilan_con\".*?</div>").ToString();
             MatchCollection matches = Regex.Matches(str, "<p.*?>(\\d+).*?</p>");
            List<Province> list = new List<Province>();
            foreach (Match match in matches)
            {
                //<p class="MsoNormal" align="justify">110000&nbsp;&nbsp;&nbsp; 北京市</p>
                var group = match.Groups[1];
                string code = group.Value;
                string name = Regex.Replace(match.ToString(), "<.*?>", "");
                name = Regex.Replace(name, "&nbsp;", "");
                name = Regex.Replace(name, code, "");
                name = name.Trim();
                if (code.EndsWith("00"))
                {
                    var temp = list.FirstOrDefault(p => p.code.StartsWith(code.Substring(0, 2)));
                    if (temp == null)
                    {
                        Province province = new Province();
                        province.code = code;
                        province.name = name;
                        province.citys = new List<City>();
                        list.Add(province);
                    }
                    else
                    {
                        string sbustr = code.Substring(0, 2);
                        Province province = list.FirstOrDefault(p => p.code.StartsWith(sbustr));
                        if (province != null)
                        {
                            City city = new City()
                            {
                                name = name,
                                code = code,
                                Counties = new List<County>()
                            };
                            province.citys.Add(city);
                        }
                        continue;
                    }
                }
                else
                {
                    string sbustr = code.Substring(0, 2);
                    Province province = list.FirstOrDefault(p => p.code.StartsWith(sbustr));
                    if (province != null)
                    {
                        City city = province.citys.FirstOrDefault(p => p.code.StartsWith(code.Substring(0,     4)));
                        if (city != null)
                        {
                            County coun = new County()
                            {
                                name = name,
                                code = code
                            };
                            city.Counties.Add(coun);
                        }
                    }
                }
            }
            Country country = new Country()
            {
                name = "中國",
                provinces = list
            };

3 獲取經緯度(縣級)

 await Task.Run(() =>
             {
                 foreach (var province in country.provinces)
                 {
                     App.Current.Dispatcher.Invoke(() =>
                     {
                         this.txtPro.Text = province.name;
                     });
                     foreach (var city in province.citys)
                     {
                         App.Current.Dispatcher.Invoke(() =>
                         {
                             this.txtCity.Text = city.name;
                         });
                         foreach (var county in city.Counties)
                         {
                             App.Current.Dispatcher.Invoke(() =>
                             {
                                 this.txtCounty.Text = county.name;
                             });
                           `  Tuple<string, string> item = CoordinateHelper.GetLocation(province.name + city.name + county.name);`
                             if (item != null)
                             {
                                 if (string.IsNullOrEmpty(item.Item1) || string.IsNullOrEmpty(item.Item2))
                                 {
                                     item = CoordinateHelper.GetLocation(province.name + city.name);
                                     //if (string.IsNullOrEmpty(item.Item1) || string.IsNullOrEmpty(item.Item2))
                                     //{
                                     //    item = CoordinateHelper.GetLocation(province.name);
                                     //}
                                 }
                                 try
                                 {
                                     county.latitude = Convert.ToDouble(item.Item1);
                                 }
                                 catch
                                 {
                                     App.Current.Dispatcher.Invoke(() =>
                                     {
                                         this.txt.Text = this.txt.Text + " " + province.name + city.name + county.name;
                                     });
                                     county.latitude = 0.0;
                                 }
                                 try
                                 {
                                     county.longitude = Convert.ToDouble(item.Item2);
                                 }
                                 catch
                                 {
                                     county.longitude = 0.0;
                                 }
                             }
                         }
                     }
                 }
             });


 public class CoordinateHelper
 {
       //{"status":0,"result":{"location":{"lng":116.23967780102,"lat":40.033162045078},"precise":0,"confidence":16,"level":"\u533a\u53bf"}}

        /// <summary>
        /// construct geo given name of a place
        /// </summary>
        /// <param name="location"></param>
        public static Tuple<string, string> GetLocation(string location)
        {
            srring ak="自己的密鑰";
            string latitude;
            string longtitude;
            location = HttpUtility.UrlEncode(location);
            string url = "http://api.map.baidu.com/geocoder/v2/?address=" + location + "&output=json&ak="+ak;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                string temp = sr.ReadToEnd();

                Match match = Regex.Match(temp, "\"location\":{\"lng\":(.*?),\"lat\":(.*?)},\"");
                longtitude = match.Groups[1].ToString();
                latitude = match.Groups[2].ToString();
            }
            return new Tuple<string, string>(latitude, longtitude);
        }

        public static string HttpHelper(string url)
        {
            string html = string.Empty;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                html = sr.ReadToEnd();
            }
            return html;
        }

    }

4 把生成的實體序列化爲josn或者xml

           string jsonStr = JsonConvert.SerializeObject(country, Newtonsoft.Json.Formatting.Indented);
            File.WriteAllText("d:\\china.json", jsonStr);
            XMLSerializeHelper.SerializeToFile(country, "d:\\china.xml");

5 xml序列化類

   public class XMLSerializeHelper
    {
        /// <summary>
        /// 序列化到文件
        /// </summary>
        public static void SerializeToFile(object obj, string filename)
        {
            string path = filename.Substring(0, filename.LastIndexOf(@"\"));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
            {
                XmlSerializer x = new XmlSerializer(obj.GetType());
                try
                {
                    x.Serialize(stream, obj);

                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }

        /// <summary>
        /// 從文件返序列化
        /// </summary>
        public static T DeserializeFromFile<T>(string path)
        {
            XmlSerializer x = new XmlSerializer(typeof(T));
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(path);
                return (T)x.Deserialize(reader);
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                reader.Close();
                reader.Dispose();
            }
        }

        /// <summary>
        /// 從XML字符串中反序列化對象
        /// </summary>
        /// <typeparam name="T">結果對象類型</typeparam>
        /// <param name="s">包含對象的XML字符串</param>
        /// <param name="encoding">編碼方式</param>
        /// <returns>反序列化得到的對象</returns>
        public static T XmlDeserialize<T>(string s, Encoding encoding)
        {
            if (string.IsNullOrEmpty(s))
            {
                throw new ArgumentNullException("反序列化字符串爲空!");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("序列化編碼爲空!");
            }

            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
            {
                using (StreamReader sr = new StreamReader(ms, encoding))
                {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }

        /// <summary>
        /// 將一個對象序列化爲XML字符串
        /// </summary>
        /// <param name="obj">要序列化的對象</param>
        /// <param name="encoding">編碼方式</param>
        /// <returns>序列化產生的XML字符串</returns>
        public static string XmlSerialize(object obj, Encoding encoding)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("序列化實體爲空!");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("序列化編碼爲空!");
            }

            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializeInternal(stream, obj, encoding);

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }
        private static void XmlSerializeInternal(Stream stream, object obj, Encoding encoding)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("序列化實體爲空!");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("序列化編碼爲空!");
            }


            XmlSerializer serializer = new XmlSerializer(obj.GetType());

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineChars = "\r\n";
            settings.Encoding = encoding;
            settings.IndentChars = "    ";

            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, obj);
            }
        }

    }

6 源碼下載

在本站搜索。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章