|
实例URLhttp://news.ifeng.com/rss/world.xml
1 public async void LoadXmlToString(string xmlData, string rssKind)
2 {
3 DateTime now = DateTime.Now;
4 Debug.WriteLine(now);
5 XElement xelem = XElement.Parse(xmlData);
6 IEnumerable items = from data in xelem.Elements("channel").Elements("item") select data;
7 string author = string.Empty;//作者
8 string title = string.Empty;//标题
9 string link = string.Empty;//详细链接
10 string pubdate = string.Empty;//发表时间
11 string description = string.Empty;//内容
12 foreach (XElement item in items)
13 {
14 News newitem = new News();
15
16 title = item.Element("title").Value;
17 //去除括号和括号中的内容
18 while (title.Contains("("))
19 {
20 int leftindex = title.IndexOf('(');
21 int rightindex = 0;
22 if (leftindex > 0)
23 {
24 rightindex = title.IndexOf(')');
25 title = title.Remove(leftindex, (rightindex - leftindex) + 1);
26 }
27 }
28 newitem.NewsTitle = title;
29
30 link = item.Element("link").Value;
31 newitem.NewsDetailLink = link;
32 }
请求数据:
1 public async Task HttpWebRequestutfString(string requestURI)
2 {
3 string ResponseData = null;
4 byte[] responseData = null;
5 try
6 {
7 Uri uri = new Uri(requestURI);
8 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
9 HttpWebResponse webResponse = (HttpWebResponse)await webRequest.GetResponseAsync();
10 Stream stream = webResponse.GetResponseStream();
11 if (stream != null)
12 {
13 List bytes = new List();
14 int temp = stream.ReadByte();
15 while (temp != -1)
16 {
17 bytes.Add((byte)temp);
18 temp = stream.ReadByte();
19 }
20 responseData = bytes.ToArray();
21 }
22 //获取字符类型的返回数据
23 ResponseData = System.Text.Encoding.UTF8.GetString(responseData, 0, responseData.Length);
24 //考虑到gb2312编码情况
25 int indexcharset = ResponseData.IndexOf("= 0) //html页面数据
29 {
30 charset = ResponseData.Substring(indexcharset, 80);
31 }
32 if (indexencoding >= 0) //xml页面数据
33 {
34 charset = ResponseData.Substring(indexencoding, 20);
35 }
36 if (charset.ToLower().Contains("gb2312") || charset.ToLower().Contains("gbk"))
37 {
38 Gb2312Encoding encoding = new Gb2312Encoding();
39 ResponseData = encoding.GetString(responseData, 0, responseData.Length).TrimEnd('\0');
40 }
41
42 }
43 catch (Exception)
44 { }
45 return ResponseData;
46
47 } |
|
|