4

I'm trying to get a list of unanswered questions from the feed, but I am having trouble reading it.

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

I hate to post such a "please fix the code" question, but I'm really stuck. I've tried several tutorials (some giving compile errors) but to no help. I assume I'm going the right way using an XmlReader and an XmlDocument as that's been a common thing from each guide.

Community
  • 1
  • 1
Ross
  • 46,186
  • 39
  • 120
  • 173
  • Can you say what errors you are getting and what it is doing incorrectly? – mmcdole Feb 01 '09 at 21:51
  • 1
    You might consider using http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx instead. – Brian Feb 01 '09 at 21:51
  • @Simucal: It's just not providing any data, no errors as such. @Brian: I looked at that and thought it was for creating feeds only. I'll give it a try. – Ross Feb 01 '09 at 22:00

1 Answers1

6

Your enumerator ienum contains only element, the <feed> element. Nothing gets added to entries since this node's name is not entry.

I'm guessing you want to iterate over the child nodes of the <feed> element instead. Try the following:

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();
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
  • Thank you, this has really helped me to understand how to iterate through XML nodes now! – Ross Feb 02 '09 at 15:37