阅读Stack Overflow RSS feed

时间:2009-02-01 21:47:07

标签: c# xml feeds xmldocument xmlreader

我正在尝试从the feed获取未回答的问题列表,但我在阅读时遇到了问题。

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的方式正确,因为这是每个指南中的常见内容。

1 个答案:

答案 0 :(得分:4)

您的枚举器ienum仅包含<feed>元素元素。没有任何内容添加到entries,因为此节点的名称不是entry

我猜你想要迭代<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();