Search code examples
c#foreachxmldocument

Foreach loop XmlNodeList


Currently I have the following code:

XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");

XmlNodeList tweets = xDoc.GetElementsByTagName("text");
foreach (int i in tweets)
{
    if (tweets[i].InnerText.Length > 0)
    {
         MessageBox.Show(tweets[i].InnerText);
    }
}

Which doesn't work, it gives me System.InvalidCastException on the foreach line.

The following code works perfectly (no foreach, the i is replaced with a zero):

XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");

XmlNodeList tweets = xDoc.GetElementsByTagName("text");

if (tweets[0].InnerText.Length > 0)
{
     MessageBox.Show(tweets[0].InnerText);
}

Solution

  • tweets is a node list. I think that what you're trying to do is this:

    XmlDocument xDoc = new XmlDocument();
    xDoc.Load("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=twitter");
    
    XmlNodeList tweets = xDoc.GetElementsByTagName("text");
    for (int i = 0; i < tweets.Count; i++)
    {
        if (tweets[i].InnerText.Length > 0)
        {
            MessageBox.Show(tweets[i].InnerText);
        }
    }