2

我正在尝试从提要中获取未回答问题的列表,但我无法阅读它。

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();

我讨厌发布这样一个“请修复代码”的问题,但我真的被困住了。我已经尝试了几个教程(有些给出了编译错误)但没有帮助。我假设我使用 anXmlReader和 an的方式是正确的,XmlDocument因为这在每个指南中都很常见。

4

1 回答 1

5

您的枚举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();
于 2009-02-01T22:52:21.887 回答