.Net/C#: 利用反射编写通用的 rss 2.0 的 reader__教程 |
|
日期:2007-5-20 1:25:45 人气:137 [大 中 小] |
|
|
|
{ get { return this._rs; } }
//用于存储所有的 RssItem private RssItem[] _RssItems;
public RssItem[] RssItems { get { return this._RssItems; } }
public void Rss(string URL) { XmlDocument xd = new XmlDocument(); //如果效率不高可采用 WebRequest 替代 xd.Load(URL); XmlNodeList xnl = xd.SelectNodes("/rss/channel");
this._rs = new RssHeader(URL);
this._TRS = typeof(RssHeader); this._tri = typeof(RssItem);
this._RssItemsAL = new ArrayList();
foreach (XmlNode xn in xnl) { //递归遍历 this.Travel(xn, 0); }
if (this._RssItemsAL.Count > 0) { this._RssItems = new RssItem[this._RssItemsAL.Count]; int i = 0; foreach (object o in this._RssItemsAL) { this._RssItems[i++] = (RssItem) o; } } }
/// /// 节点 /// 项目数 private void Travel(XmlNode xn, int i) { if (xn.HasChildNodes) { foreach (XmlNode x in xn.ChildNodes) { if (x.ParentNode != null) { if (x.ParentNode.Name == "channel") { if (x.Name == "item") { i ++; if (i >= 1) { XmlNode node = null; bool b = false; //是否是 Rss Item RssItem ri = null; if (i == 1) //Header { node = xn; b = false; } else if (i > 1) //Item { node = x; b = true; ri = new RssItem(); }
foreach (XmlNode n in node.ChildNodes) { if (n.Name != "item") { if (!b) //Rss Header Header { //根据 XML 实际存在的属性,利用反射为 RssHeader 实例的私有成员赋值 FieldInfo fi = this._TRS.GetField("_" + n.Name.Replace(":","") ,BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); if (fi != null) { fi.SetValue(this._rs,n.InnerText); } } else //Rss Item { //根据 XML 实际存在的属性,利用反射为 RssItem 实例的私有成员赋值 FieldInfo fi = this._tri.GetField("_" + n.Name.Replace(":",""),BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); if (fi != null) { fi.SetValue(ri,n.InnerText); } }
} } if (!b) { //触发 RssHeaderReceive 事件 if (this.RssHeaderReceive != null) { this.RssHeaderReceive(this,this._rs); } } else { //制定 RssItem 实例的 Header/Header FieldInfo fi = this._tri.GetField("_Header",BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); if (fi != null) { fi.SetValue(ri,this._rs); }
//触发 RssItemReceive 事件 if (this.RssItemReceive != null) { this.RssItemReceive(this,ri); } this._RssItemsAL.Add(ri); } } } } } if (!x.HasChildNodes) { this.Travel(x, i); } } } } }
public class Util { public static DateTime ParseDateTime(string s) { DateTime dt; if (s == null || s.ToString().Length <= 0) { dt = DateTime.Now; |
|
出处:本站原创 作者:佚名 |
|
|