【问题标题】:Reading the Stack Overflow RSS feed阅读 Stack Overflow RSS 提要
【发布时间】:2010-10-04 20:06:27
【问题描述】:

我正在尝试从 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 的方式是正确的,因为这在每个指南中都很常见。

【问题讨论】:

  • 你能说出你遇到了什么错误以及它做错了什么吗?
  • 您可以考虑改用msdn.microsoft.com/en-us/library/…
  • @Simucal:它只是没有提供任何数据,没有错误。 @Brian:我看了看,认为它仅用于创建提要。我试试看。

标签: c# xml feed xmldocument xmlreader


【解决方案1】:

您的枚举器 ienum 仅包含元素 &lt;feed&gt; 元素。由于该节点的名称不是 entry,因此不会向 entries 添加任何内容。

我猜你想迭代 &lt;feed&gt; 元素的子节点。请尝试以下操作:

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 节点!
猜你喜欢
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多