C#实现解析百度天气数据,Rss解析百度新闻以及根据IP获取所在城

2019-12-26 11:59:43于丽

相关

 

复制代码 var ip = Request.UserHostAddress;
using (var client = new WebClient())
{
 var url = "http://www.easck.com/service/getIpInfo.php?ip=" + ip;
 client.Encoding = Encoding.UTF8;
 var str = client.DownloadString(url);
 Response.Write(str);
}

 

这样我们就可以获取到客户所在城市的天气数据了。

三、获取百度新闻

最近还有个小需求,获取某某新闻数据,楼主习惯性的查了下百度的相关资料,能通过Rss来获取百度新闻数据。

接口地址:http://www.easck.com/n?cmd=7&loc=0&name=%B1%B1%BE%A9&tn=rss

打开后,查看它的源,无非就是xml文件,我们可以将xml文件,序列化成对象,如果没有接触过这类知识,可以看下《xml与对象的序列化和反序列化》。

根据它的源,就能轻松定义出数据结构。

 

复制代码 [XmlRoot("rss")]
public class Rss
{
        public Channel channel { get; set; }
}
[XmlRoot("channel")]
public class Channel
{
        public string title { get; set; }
        public BaiduImage image { get; set; }
        public string link { get; set; }
        public string description { get; set; }
        public string language { get; set; }
        public string lastBuildDate { get; set; }
        public string docs { get; set; }
        public string generator { get; set; }
        [XmlElement]
        public List<Channel_Item> item { get; set; }
}

 

public class BaiduImage
{
        public string title { get; set; }
        public string link { get; set; }
        public string url { get; set; }
}

public class Channel_Item