C# XmlTextReader and DataSet causing Duplicate Name Exception
I'm trying to read a standard CNN news feed to put into a table, and it's telling me "duplicate 'link' column exception." on the line:
cnnds.ReadXml(CNNfeed);
Here's the whole code, and it stops the code and throws errors, when it should simply just ignore duplicate columns or use the last column.
XmlTextReader CNNfeed = new XmlTextReader("http://rss.cnn.com/rss/cnn_topstories.rss");
DataSet cnnds = new DataSet("CNN");
cnnds.ReadXml(CNNfeed, XmlReadMode.Auto); // read the XML feed
DataTable CNNNewsFeedTable = new DataTable("CNNNewsFeed");
How do I resolve this issue? I've tried everything, and the only way to get this to work is to properly not use the CNN feed.
I just changed XmlReadMode.ReadSchema and it got through this part but then it says cnnds.Tables[1] is an index out of range. Like as if it's an empty XML.
Is there any easier way to read RSS feeds from other websites without all these exceptions and probl开发者_开发问答ems?
Edit: It seems adding a try { } catch() around it, however redundant, seems to bypass this problem.
If you want to read the xml in a dataset, then you need the xml-schema (else ReadXml() can't distinguish between the different namespaces).
Use:
var CNNfeed = new XmlTextReader("http://rss.cnn.com/rss/cnn_topstories.rss");
var cnnds = new DataSet("CNN");
cnnds.ReadXmlSchema("http://www.thearchitect.co.uk/schemas/rss-2_0.xsd"); // read the rss schema
cnnds.ReadXml(CNNfeed); // read the XML feed
But I think you'd better use xpath to find the information you need:
var doc = XDocument.Load("http://rss.cnn.com/rss/cnn_topstories.rss");
foreach (XElement node in (IEnumerable) doc.XPathEvaluate("//item"))
{
Console.WriteLine(node.XPathSelectElement("title").Value);
}
精彩评论