前几天在搞rss的解析,碰到一些问题
现在RSS很流行,一度风行于整个互联网,的确,他给我们带来了很大的改变和方便!RSS也分很多版本,rss.1.0.rss2.0比较多,还有atom格式的!
在解析的时候给我带来了麻烦,由于本人没有怎么研究过xml和相关的解析工作,所以碰到很多问题,目前能成功解析rss2.0。
顶部的一些解析(暂时这么叫吧,我也不知道叫什么)
1private void GetRssHead(XmlDocument doc)
2 {
3 //XmlDocument doc = new XmlDocument();
4 //doc.LoadXml(this.RssXmlStr);
5 XmlElement elem = (XmlElement)doc.DocumentElement.FirstChild;
6 this.headtitle=elem.SelectSingleNode("title").InnerText;
7 this.headurl=elem.SelectSingleNode("link").InnerText;
8 this.headdescription=elem.SelectSingleNode("description").InnerText;
9
10 }
内容的解析:
2 {
3 //XmlDocument doc = new XmlDocument();
4 //doc.LoadXml(this.RssXmlStr);
5 XmlElement elem = (XmlElement)doc.DocumentElement.FirstChild;
6 this.headtitle=elem.SelectSingleNode("title").InnerText;
7 this.headurl=elem.SelectSingleNode("link").InnerText;
8 this.headdescription=elem.SelectSingleNode("description").InnerText;
9
10 }
1 private void ParseItems()
2 {
3 XmlDocument doc = new XmlDocument();
4 doc.LoadXml(this.RssXmlStr);
5 XmlNodeList nodeList;
6 XmlElement root = doc.DocumentElement;
7 nodeList = root.GetElementsByTagName("item");
8 for(int n=0;n<nodeList.Count;n++)
9 {
10 listtitle.Add(nodeList[n].SelectSingleNode ("title").InnerText);
11 listlink.Add(nodeList[n].SelectSingleNode ("link").InnerText);
12 listdescription.Add(nodeList[n].SelectSingleNode ("description").InnerText);
13 }
14 }
但是对于rss1.0我目前只能这样处理:2 {
3 XmlDocument doc = new XmlDocument();
4 doc.LoadXml(this.RssXmlStr);
5 XmlNodeList nodeList;
6 XmlElement root = doc.DocumentElement;
7 nodeList = root.GetElementsByTagName("item");
8 for(int n=0;n<nodeList.Count;n++)
9 {
10 listtitle.Add(nodeList[n].SelectSingleNode ("title").InnerText);
11 listlink.Add(nodeList[n].SelectSingleNode ("link").InnerText);
12 listdescription.Add(nodeList[n].SelectSingleNode ("description").InnerText);
13 }
14 }
1 //头部
2 nodeList = root.GetElementsByTagName("channel");
3 this.headtitle=nodeList[0].ChildNodes[0].InnerText;
4 this.headurl=nodeList[0].ChildNodes[1].InnerText;
5 this.headdescription=nodeList[0].ChildNodes[2].InnerText;
6
不能用SelectSingleNode来取元素,这样RSS变了顺序就不行了,还有Atom格式的一样也没处理好!
2 nodeList = root.GetElementsByTagName("channel");
3 this.headtitle=nodeList[0].ChildNodes[0].InnerText;
4 this.headurl=nodeList[0].ChildNodes[1].InnerText;
5 this.headdescription=nodeList[0].ChildNodes[2].InnerText;
6
新浪微博:http://t.sina.com.cn/sunli1223