Foreach loop XmlNodeList

Devator picture Devator · Aug 7, 2012 · Viewed 69.2k times · Source

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

Answer

YAYAYAYA picture YAYAYAYA · Aug 7, 2012

I know that there is already a marked answer, but you can do it like you did in your first try, you just need to replace the int with XmlNode

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

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