今天写了一个简单的新浪新闻RSS操作类库

2024-03-20 01:38

本文主要是介绍今天写了一个简单的新浪新闻RSS操作类库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天,有位群友问我如何获新浪新闻列表相关问题,我想,用正则表达式网页中取显然既复杂又不一定准确,现在许多大型网站都有RSS集合,所以我就跟他说用RSS应该好办一些。

 

一年前我写过一个RSS阅读器,不过,打新浪相关的XML文件看了一下,发现RSS2.0 和一年前的不大一样了,但具体怎么处理,几句话也很难讲得清楚,所以,我干脆写了一个类库给他,直接调用。

 

类库不是很复杂,主要两个功能:

一、通过新浪的根频道XML在把所有频道的信息读出来,使用递归连同子节点也读取出来。

二、指定频道URL的XML文件来获取新闻信息。

 

首先,我们写两个类,一个用于保存新闻个息,另一个用于保存频道信息。

    /// <summary>
/// 新闻记录实体
/// </summary>
[Serializable]
public  class NewsItem
{
/// <summary>
/// 新闻标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 新闻链接
/// </summary>
public string Link { get; set; }
/// <summary>
/// 作者
/// </summary>
public string Author { get; set; }
/// <summary>
/// 分类
/// </summary>
public string Category { get; set; }
/// <summary>
/// 发布时间
/// </summary>
public DateTime PubDate { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 其它说明
/// </summary>
public string Comments { get; set; }
}


 

    /// <summary>
/// 新闻频道列表 
/// </summary>
[Serializable]
public  class OutLine
{
/// <summary>
/// 频道标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 频道文本
/// </summary>
public string Text { get; set; }
/// <summary>
/// 频道类型-RSS
/// </summary>
public string Type { get; set; }
/// <summary>
/// XML地址
/// </summary>
public string xmlUrl { get; set; }
/// <summary>
/// HTML地址
/// </summary>
public string htmlUrl { get; set; }
private List<OutLine> _olChildren = new List<OutLine>();
/// <summary>
/// 子频道
/// </summary>
public List<OutLine> ChildrenOutline
{
get { return _olChildren; }
}
}


 

好,接下来对应的两类,分别获取频道列表和新闻列表。

    /// <summary>
/// 新闻项管理类
/// </summary>
public class NewsManager
{
/// <summary>
/// 根据输入的XML地址获取新闻列表。
/// </summary>
/// <param name="xmlUrl">新闻频道的XML地址</param>
/// <returns>NewsItem的结果集合</returns>
public List<NewsItem> GetNewsItemList(string xmlUrl)
{
List<NewsItem> _myNews = new List<NewsItem>();
XElement myRoot = XElement.Load(xmlUrl);
var theItems =
from xe in myRoot.Element("channel").Elements("item")
select xe;
foreach (XElement e in theItems)
{
_myNews.Add(new NewsItem()
{
Title = (string)e.Element("title"),
Link = (string)e.Element("link"),
Author = (string)e.Element("author"),
Category = (string)e.Element("category"),
PubDate = (DateTime)e.Element("pubDate"),
Comments = (string)e.Element("comments"),
Description = (string)e.Element("description")
});
}
return _myNews;
}
}


 

    /// <summary>
/// 自动获取频道列表类
/// </summary>
public class OutlineManager
{
/// <summary>
/// 获取频道列表,包含子节点
/// </summary>
/// <param name="xmlUrl">根频道地址</param>
/// <returns></returns>
public List<OutLine> GetCannels(string xmlUrl)
{
List<OutLine> _list = new List<OutLine>();
XElement root = XElement.Load(xmlUrl);
var firstOutline = root.Element("body").Elements("outline");
foreach (XElement xitem in firstOutline)
{
OutLine myRootOutline = new OutLine
{
Title = (string)xitem.Attribute("title") ?? "",
Text = (string)xitem.Attribute("text") ?? "",
Type = (string)xitem.Attribute("type") ?? "",
xmlUrl = (string)xitem.Attribute("xmlUrl") ?? "",
htmlUrl = (string)xitem.Attribute("htmlUrl") ?? ""
};
AddChildElements(xitem, myRootOutline);
_list.Add(myRootOutline);
}
return _list;
}
private void AddChildElements(XElement xNode, OutLine ol)
{
if (xNode == null) return;
var xc = xNode.Elements("outline");
// 递归,添加子节点
foreach (XElement xe in xc)
{
OutLine outline = new OutLine()
{
Title = xe.Attribute("title").Value,
Text = xe.Attribute("text").Value,
Type = xe.Attribute("type").Value,
xmlUrl = xe.Attribute("xmlUrl").Value,
htmlUrl = xe.Attribute("htmlUrl").Value
};
ol.ChildrenOutline.Add(outline);
AddChildElements(xe, outline);
}
}
}


 

OK,简单的类库写好了,程序集名称为SinaRssAPIs_CS,然后,我们建一个程序来测试一下。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SinaRssAPIs_CS;
namespace NewsApiTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
this.Text = "新浪RSS类库示例程序";
this.treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
this.dataGridView1.AutoGenerateColumns = false; //不自动创建列
//添加列
DataGridViewTextBoxColumn colTitle = new DataGridViewTextBoxColumn();
colTitle.HeaderText = "新闻标题";
colTitle.DataPropertyName = "Title";
this.dataGridView1.Columns.Add(colTitle);
DataGridViewTextBoxColumn colDesc = new DataGridViewTextBoxColumn();
colDesc.HeaderText = "描述";
colDesc.DataPropertyName = "Description";
colDesc.Width = 280;
this.dataGridView1.Columns.Add(colDesc);
DataGridViewTextBoxColumn colDate = new DataGridViewTextBoxColumn();
colDate.DefaultCellStyle.Format = "yyyy-MM-dd";
colDate.HeaderText = "发布日期";
colDate.DataPropertyName = "PubDate";
this.dataGridView1.Columns.Add(colDate);
DataGridViewTextBoxColumn colAuthor = new DataGridViewTextBoxColumn();
colAuthor.HeaderText = "发布者";
colAuthor.DataPropertyName = "Author";
this.dataGridView1.Columns.Add(colAuthor);
DataGridViewTextBoxColumn colLink = new DataGridViewTextBoxColumn();
colLink.DataPropertyName = "Link";
colLink.Name = "link";
colLink.Visible = false;
this.dataGridView1.Columns.Add(colLink);
this.dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);
}
void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (this.dataGridView1.CurrentRow == null) return;
string link = this.dataGridView1.CurrentRow.Cells["link"].Value.ToString();
this.webBrowser1.Navigate(link);
}
void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node.Tag == null) return;
string xml = e.Node.Tag.ToString();
List<NewsItem> items = null;
NewsManager mg = new NewsManager();
items = mg.GetNewsItemList(xml);
this.dataGridView1.DataSource = items;
}
private void Form1_Load(object sender, EventArgs e)
{
OutlineManager omg = new OutlineManager();
List<OutLine> cnList = omg.GetCannels(@"http://rss.sina.com.cn/sina_all_opml.xml");
this.treeView1.BeginUpdate();
this.treeView1.Nodes.Clear();
//根节点
foreach (OutLine  root in cnList)
{
TreeNode tnRoot = new TreeNode();
tnRoot.Text = root.Title.Split('-')[0];
AddNodes(root, tnRoot);
this.treeView1.Nodes.Add(tnRoot);
}
this.treeView1.EndUpdate();
}
private void AddNodes(OutLine ol, TreeNode nd)
{
foreach (OutLine oits in ol.ChildrenOutline)
{
TreeNode tn = new TreeNode();
tn.Text = oits.Title;
tn.Tag = oits.xmlUrl;
AddNodes(oits, tn);
nd.Nodes.Add(tn);
}
}
}
}


大致的运行效果如下:

 

现在,我说一下技术要点,不多,就一个,对,就是LinQ To XML。

这篇关于今天写了一个简单的新浪新闻RSS操作类库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/827897

相关文章

Python调用Orator ORM进行数据库操作

《Python调用OratorORM进行数据库操作》OratorORM是一个功能丰富且灵活的PythonORM库,旨在简化数据库操作,它支持多种数据库并提供了简洁且直观的API,下面我们就... 目录Orator ORM 主要特点安装使用示例总结Orator ORM 是一个功能丰富且灵活的 python O

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

redis群集简单部署过程

《redis群集简单部署过程》文章介绍了Redis,一个高性能的键值存储系统,其支持多种数据结构和命令,它还讨论了Redis的服务器端架构、数据存储和获取、协议和命令、高可用性方案、缓存机制以及监控和... 目录Redis介绍1. 基本概念2. 服务器端3. 存储和获取数据4. 协议和命令5. 高可用性6.

轻松上手MYSQL之JSON函数实现高效数据查询与操作

《轻松上手MYSQL之JSON函数实现高效数据查询与操作》:本文主要介绍轻松上手MYSQL之JSON函数实现高效数据查询与操作的相关资料,MySQL提供了多个JSON函数,用于处理和查询JSON数... 目录一、jsON_EXTRACT 提取指定数据二、JSON_UNQUOTE 取消双引号三、JSON_KE

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav

C++实现封装的顺序表的操作与实践

《C++实现封装的顺序表的操作与实践》在程序设计中,顺序表是一种常见的线性数据结构,通常用于存储具有固定顺序的元素,与链表不同,顺序表中的元素是连续存储的,因此访问速度较快,但插入和删除操作的效率可能... 目录一、顺序表的基本概念二、顺序表类的设计1. 顺序表类的成员变量2. 构造函数和析构函数三、顺序表

使用C++实现单链表的操作与实践

《使用C++实现单链表的操作与实践》在程序设计中,链表是一种常见的数据结构,特别是在动态数据管理、频繁插入和删除元素的场景中,链表相比于数组,具有更高的灵活性和高效性,尤其是在需要频繁修改数据结构的应... 目录一、单链表的基本概念二、单链表类的设计1. 节点的定义2. 链表的类定义三、单链表的操作实现四、

Python利用自带模块实现屏幕像素高效操作

《Python利用自带模块实现屏幕像素高效操作》这篇文章主要为大家详细介绍了Python如何利用自带模块实现屏幕像素高效操作,文中的示例代码讲解详,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、获取屏幕放缩比例2、获取屏幕指定坐标处像素颜色3、一个简单的使用案例4、总结1、获取屏幕放缩比例from