阅读 Stack Overflow 的 RSS 源代码

4
我正在尝试从提要中获取未回答的问题列表,但我无法阅读它。
const string RECENT_QUESTIONS = "https://stackoverflow.com/feeds";

XmlTextReader reader;
XmlDocument doc;

// Load the feed in
reader = new XmlTextReader(RECENT_QUESTIONS);
//reader.MoveToContent();

// Add the feed to the document
doc = new XmlDocument();
doc.Load(reader);

// Get the <feed> element
XmlNodeList feed = doc.GetElementsByTagName("feed");

// Loop through each item under feed and add to entries
IEnumerator ienum = feed.GetEnumerator();
List<XmlNode> entries = new List<XmlNode>();
while (ienum.MoveNext())
{
    XmlNode node = (XmlNode)ienum.Current;
    if (node.Name == "entry")
    {
        entries.Add(node);
    }
}

// Send entries to the data grid control
question_list.DataSource = entries.ToArray();

我不太愿意发这种“请修复代码”的问题,但是我真的卡住了。我尝试了几个教程(有些会给出编译错误),但没有帮助。我认为我正走在正确的路上,使用XmlReaderXmlDocument,因为每个指南都提到了这一点。


你能说出你遇到了哪些错误以及它的具体表现吗? - mmcdole
1
你可以考虑使用http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx。 - Brian
@Simucal:它只是没有提供任何数据,没有任何错误。 @Brian:我看了一下,认为它只是用于创建RSS源。我会尝试一下的。 - Ross
1个回答

6
你的枚举器ienum只包含一个元素,即<feed>元素。由于此节点的名称不是entry,因此不会将任何内容添加到entries中。
我猜想你想遍历<feed>元素的子节点。请尝试以下操作:
const string RECENT_QUESTIONS = "http://stackoverflow.com/feeds";

XmlTextReader reader;
XmlDocument doc;

// Load the feed in
reader = new XmlTextReader(RECENT_QUESTIONS);
//reader.MoveToContent();

// Add the feed to the document
doc = new XmlDocument();
doc.Load(reader);

// Get the <feed> element.
XmlNodeList feed = doc.GetElementsByTagName("feed");
XmlNode feedNode = feed.Item(0);

// Get the child nodes of the <feed> element.
XmlNodeList childNodes = feedNode.ChildNodes;
IEnumerator ienum = childNodes.GetEnumerator();

List<XmlNode> entries = new List<XmlNode>();

// Iterate over the child nodes.
while (ienum.MoveNext())
{
    XmlNode node = (XmlNode)ienum.Current;
    if (node.Name == "entry")
    {
        entries.Add(node);
    }
}

// Send entries to the data grid control
question_list.DataSource = entries.ToArray();

谢谢,这确实帮助我理解如何遍历XML节点了! - Ross

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接