Converting RSS feed into DataTable
嗨,我正在阅读RSS feed,并使用DataTable创建XML。 这是我的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | try { DataTable tbl = new DataTable(); tbl.Columns.Add("id"); tbl.Columns.Add("product_name"); tbl.Columns.Add("description"); //Extra Nodes tbl.Columns.Add("brand"); tbl.Columns.Add("condition"); tbl.Columns.Add("product_type"); XmlDocument doc = new XmlDocument(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(s); XmlNodeList itemNodes = xmlDoc.SelectNodes("//rss/channel/item"); foreach (XmlNode itemNode in itemNodes) { DataRow row = tbl.NewRow(); XmlNode idNode = itemNode.SelectSingleNode("id"); XmlNode product_nameNode = itemNode.SelectSingleNode("product_name"); XmlNode descriptionNode = itemNode.SelectSingleNode("description"); //extra nodes XmlNode brandNode = itemNode.SelectSingleNode("brand"); XmlNode conditionNode = itemNode.SelectSingleNode("condition"); XmlNode product_typeNode = itemNode.SelectSingleNode("product_type"); if (idNode != null && product_nameNode != null && descriptionNode != null ) { row[0] = idNode.InnerText; row[1] = product_nameNode.InnerText; row[2] = descriptionNode.InnerText; //extra nodes if (brandNode == null) row[3] =""; else row[3] = brandNode.InnerText; if (conditionNode==null) row[4] =""; else row[4] = conditionNode.InnerText; if (product_typeNode==null) row[5] =""; else row[5] = product_typeNode.InnerText; } tbl.Rows.Add(row); // tbl.Rows.Add(row); } } } catch (Exception ex) { // Console.WriteLine(ex.Message); // Console.Read(); } |
这工作正常,没有任何问题,但是我想提高代码效率。 这是读取Rss并添加到数据表中的好方法吗? 我正在VS 2008上进行SSIS项目,因此无法使用SyndicationFeed。
您可以在下面的代码中使用此代码并作为示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System; using System.ServiceModel.Syndication; using System.Xml; namespace RSSFeed { public class Program { static void Main(string[] args) { // URL from the site you need (RSS Feed in XML please). String url ="http://www.medicalnewstoday.com/rss/abortion.xml"; // Create XML Reader. using (XmlReader xmlReader = XmlReader.Create(url, new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore })) { // Load The Feed. SyndicationFeed syndicationFeed = SyndicationFeed.Load(xmlReader); // through the list. foreach (SyndicationItem item in syndicationFeed.Items) { // You can use a lot of information here todo what you need. // TODO... // Examples String subject = item.Title.Text; String summary = item.Summary.Text; } xmlReader.Close(); } } } } |