从国家统计局采集最新行政区划分

最近一新项目要用到国内行政区划数据,bing了一下,已有网友提供sql版本数据下载,但在本地查看数据不够新,至少我老家所在市2010年改名儿了这数据也看不到。所以说呢还是自己动手丰衣足食。 使用了JSON.NET

1、

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace DivisonsOfPRC
{
    /// <summary>
    /// 演示代码,不建议在生产环境使用,请搜HttpClient
    /// </summary>
    public class Http
    {
        public string GET(string url)
        {
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
            hwr.Method = "GET";
            hwr.CookieContainer = new CookieContainer();
            hwr.Accept = "*/*";
            hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN");

            hwr.Referer = "http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/";
            hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.UTF8;
            StreamReader readStream = new StreamReader(receiveStream, encode);

            String linesOfHTML = readStream.ReadToEnd();
            //System.Console.WriteLine(linesOfHTML);
            //System.Console.ReadKey();

            receiveStream.Close();
            response.Close();
            readStream.Close();
            return linesOfHTML;
        }
    }
}

生成JSON.NET

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace DivisonsOfPRC
{
    /// <summary>
    /// 演示代码,不建议在生产环境使用,请搜HttpClient
    /// </summary>
    public class Http
    {
        public string GET(string url)
        {
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
            hwr.Method = "GET";
            hwr.CookieContainer = new CookieContainer();
            hwr.Accept = "*/*";
            hwr.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN");

            hwr.Referer = "http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/";
            hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.UTF8;
            StreamReader readStream = new StreamReader(receiveStream, encode);

            String linesOfHTML = readStream.ReadToEnd();
            //System.Console.WriteLine(linesOfHTML);
            //System.Console.ReadKey();

            receiveStream.Close();
            response.Close();
            readStream.Close();
            return linesOfHTML;
        }
    }
}

测试用例:

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace DivisonsOfPRC
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] directs = new string[] { "北京市", "天津市", "上海市", "重庆市" };
            Http http = new Http();
            //1.采集html到本地
            string html = http.GET("http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201401/t20140116_501070.html");
            //System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "dop.html", html, Encoding.UTF8);

            //2.分析html
            //可以用HtmlAgilePack找到行政区划数据的核心html
            //我这里就不演示HAP怎么使用了,咱简单点儿,就用字符串分析截取
            int startIndex = html.LastIndexOf("TRS_Editor");
            startIndex = html.IndexOf("<p class=\"", startIndex);
            html = html.Substring(startIndex);
            html = html.Substring(0, html.IndexOf("</div>"));

            //真正分析省市区逻辑
            string[] lines = html.Split(new string[] { "</p>" }, StringSplitOptions.RemoveEmptyEntries);
            string code = null, name= null,line = null;

            List<Node> nodes = new List<Node>();
            Node PrevCity = null;
            Node PrevProvince = null;
            for (int i = 0; i < lines.Length; i++)
            {
                Node nod = new Node();
                line = ExtractHtml(lines[i], "align=\"justify\">", "");
                code = line.Substring(0, line.IndexOf("&"));
                name = line.Substring(line.LastIndexOf(";")+1).Trim();
                nod.code = code;
                nod.name = name;

                int timesOfSpaceOccure = CountString(line, "&nbsp;");
                nod.spaces = timesOfSpaceOccure;
                if (timesOfSpaceOccure == 3)
                {
                    nodes.Add(nod);
                    PrevProvince = nod;
                    PrevCity = null;
                }
                else
                {
                    if (timesOfSpaceOccure > PrevProvince.spaces)
                    {
                        //下一级别
                        if (PrevCity != null && timesOfSpaceOccure > PrevCity.spaces)
                        {
                            if (PrevCity.cell == null)
                            {
                                PrevCity.cell = new List<Node>();
                            }
                            PrevCity.cell.Add(nod);
                        }
                        else
                        {
                            //市
                            if (PrevProvince.cell == null)
                            {
                                PrevProvince.cell = new List<Node>();
                            }
                            PrevProvince.cell.Add(nod);
                            PrevCity = nod;
                        }
                    }
                }

            }
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            string json2 = JsonConvert.SerializeObject(nodes, Newtonsoft.Json.Formatting.None, settings);
            System.IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "data.js", json2, Encoding.UTF8);
        }

        static string ExtractHtml(string source, string prefix, string suffix)
        {
            if (string.IsNullOrEmpty(source))
            {
                return null;
            }
            int startIndex = source.IndexOf(prefix);
            if (startIndex == -1)
            {
                return string.Empty;
            }
            startIndex = startIndex + prefix.Length;
            int endIndex = source.Length;
            if (!string.IsNullOrEmpty(suffix))
            {
                endIndex = source.IndexOf(suffix, startIndex);
                if (endIndex == -1)
                {
                    //suffix not found
                    return string.Empty;
                }
            }
            return source.Substring(startIndex, endIndex - startIndex);
            //return null;
        }

        static int CountString(string source, string search)
        {
            int count = 0;
            int startIndex = 0;
            startIndex = source.IndexOf(search);
            while (startIndex != -1)
            {
                startIndex = source.IndexOf(search, startIndex + search.Length);
                count++;
            }
            return count;
        }
    }
}

留下备用

时间: 2025-01-16 05:55:29

从国家统计局采集最新行政区划分的相关文章

mysql-省市区县-中华人民共和国统计局-最新行政区域划分-有需要其他的格式的,留下联系方式

insert into t_province (ProvinceCode,ProvinceName) values ('410000','河南省'); insert into t_province (ProvinceCode,ProvinceName) values ('420000','湖北省'); insert into t_province (ProvinceCode,ProvinceName) values ('422800','恩施土家族苗族自治州'); insert into t_p

中国社会9个阶层划分

历史上有各社会阶层及地位等级群体的高低等级排列,现实生活中有没有呢?仅管没有固定的标准和权威的说法,但民间高手出台的版本也不i这是网络上出现的一个中国社会最新阶层划分模型,迥异于史上曾有的那些阶层划分,模式和方法均不同,仅供大家娱乐……(申明本文引自网络,非新秀网观点) 1级:以在任委员.退休常委为代表,和2的区别在于,1对全国局势有控制能力,2没有. 2级:以在任实权省部级干部.退休委员.部分大权贵.大富商.大银行家为代表.和3的区别在于,2能影响国家政策,3不能. 3级:以一般省部.副省部.

中国社会的9个阶层划分

1. 来自知乎的分析 历史上有各社会阶层及地位等级群体的高低等级排列,现实生活中有没有呢?仅管没有固定的标准和权威的说法,但民间高手出台的版本也不i这是网络上出现的一个中国社会最新阶层划分模型,迥异于史上曾有的那些阶层划分,模式和方法均不同,仅供大家娱乐--(申明本文引自网络,非本人观点) 1级:以在任委员.退休常委为代表,和2的区别在于,1对全国局势有控制能力,2没有. 2级:以在任实权省部级干部.退休委员.部分大权贵.大富商.大银行家为代表.和3的区别在于,2能影响国家政策,3不能. 3级:

SEO优化之如何利用百度风云榜获取百万流量

SEO优化之如何利用百度风云榜获取百万流量 (     SEO优化一定要精细,一味的趁波逐浪最后别说分一杯羹了,可能连汤都看不到.下面我们来说一下网站优化如何运用热度风云榜,并晋升网站流量. 为什么会说到风云榜,所谓的风云榜实在就是天天发生的最新事件,如娱乐.糊口等热点搜索内容的集合.且能够非常正确的反映用户关注的信息及内容. 第一:百度风云榜 百度一下你就知道,这已经成为良多人的口头禅,只要登录百度账号在首页就可以显示实时热门百度优化之怎样利用百度风云榜百度优化之怎样利用百度风云榜.百度风云榜

高效房产中介信息管理软件------房产小蜜书功能简介

房产小蜜书是一款拥有多功能,操作简单,高效率的房产中介信息管理软件,同时,它又是一款营销软件,可以通过云刷新的功能实现云端的自动刷新,让经纪人们告别手动刷新的重复工作.下面就是对房产小蜜书主要功能的介绍. 房产小蜜书的主要功能有: (1) 站点管理:注册需要发布房源的网站,然后将网站的账号与房产小蜜书进行绑定,这是使用房产小蜜书进行信息管理和营销等操作的前提. 图1-1 站点管理 (2)房源信息录入:房源信息录入的作用是讲房源信息存入小蜜书的资料库中:特色在于: 填写小区名称后自动匹配小区区域.

北京豪宅市场调查:多项目集中放量使选择面加大

北京豪宅市场调查:多项目集中放量使选择面加大 行业动态腾讯房产刘佳 郭韦 王怡2014-09-26 07:56 我要分享 0 虽然今年楼市市场整体低迷,但高端住宅市场表现向好.据机构统计显示,8月北京别墅成交套数为260套,环比上升26.8%,成交面积也达为69720平方米,环比上涨3.6%,成交均价达36384元/平方米,环比上涨幅度达到11.2%.除去保利·海德公园外,中赫·万柳书院及万科甲柒拾柒号也将在今年年底前入市,无形之中催热豪宅市场,并提高了豪宅市场价格段位.那么北京豪宅市场具体情况

JAVA验证身份证号码是否合法

package com.chauvet.utils; import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.Map;import java.util.regex.Match

读图时代,专业图片素材搜索引擎的构造方法漫谈。

用搜索引擎这个标题,可能太大,但是在这个信息爆炸的时代,专业的搜索引擎越来越有必要.我个人做图片也有10年的历史了,想想从最初都购买素材光盘的时代,到现在使用搜索引擎搜索图片素材,两者其实各有优缺点,购买的素材光盘都是经过整理的非常规范有序,缺点是素材容量有限,而且还需要付费,而使用搜索引擎可以搜索到海量的图片素材,大部分还是免费的,但是在如今这个信息化的时代,在海量垃圾信息的干扰下,获得真实有效的图片素材的时间成本越来越高了.由于当前的图片搜索主要是依靠图片的相关描述来的,所以经常会出现我们使

校验身份证号码(转载)

1 public class IDCardVerify { 2 3 private String errorInfo; 4 5 // wi =2(n-1)(mod 11) 6 final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 }; 7 // verify digit 8 final int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 }; 9 private