现在的位置: 首页 > 综合 > 正文

windows phone 7,sliverlight 下载网页的解析,关于wp7 gb2312编码

2012年11月27日 ⁄ 综合 ⁄ 共 1201字 ⁄ 字号 评论关闭

关于silverlight和wp7(windows phone 7)是默认不支持gb2312解码的,

所以从网上下载的Html大部分都是乱码。

例如:http://news.sina.com.cn/s/2011-11-25/120923524756.shtml

下面是演示一个wp7程序

 1    WebClient webClenet=new WebClient();
2 webClenet.DownloadStringAsync(new Uri("http://news.sina.com.cn/s/2011-11-25/120923524756.shtml", UriKind.RelativeOrAbsolute));
3 webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);
4
5
6
7
8
9
10 回调事件:
11 void webClenet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
12 {
13 string s= e.Result;
14 }

调试发现

 

几乎全部是乱码问题.

将编码设为utf-8同样是乱码。

于是引用了一个开源的库HtmlAgilityPack(包含编码还处理HTML节点)

下载地址为:http://www.codeplex.com/htmlagilitypack

将HtmlAgilityPack.dll引用到项目中,这时会弹出一个提示,大概就是这不是一个windows phone的类库,不理会,直接确定。

然后修改一下我们的代码

  WebClient webClenet=new WebClient();
           webClenet.Encoding = new HtmlAgilityPack.Gb2312Encoding(); //加入这句设定编码
           webClenet.DownloadStringAsync(new Uri("http://news.sina.com.cn/s/2011-11-25/120923524756.shtml", UriKind.RelativeOrAbsolute));     
           webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);

 

调试一下,结果如图:

 

终于看到我们的中文啦。

同时,HtmlAgilityPack不仅帮我们解决了gb2312的编码问题,它还是我们解析HTML的利器哦~!  

 

 

 

不好意思,之前忘记补上案例了,今天补上

下载地址

http://115.com/file/e6abw15h 

 

 

抱歉!评论已关闭.