Foreach loop XmlNodeList

Viewed 77219

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);
}
7 Answers
foreach (XmlNode node in tweets)
{
    if (tweets[i].InnerText.Length > 0)
    {
         MessageBox.Show(tweets[node].InnerText);
    }
}

I've changed the 'I', which you cannot use, to XmlNode, which selects a single line of your list.

You can loop through the Collection with .GetEnumerator()

this code is taken Microsoft Documentation :

 XmlNodeList elemList = root.GetElementsByTagName("title");
 IEnumerator ienum = elemList.GetEnumerator();          
 while (ienum.MoveNext()) {   
   XmlNode title = (XmlNode) ienum.Current;
   Console.WriteLine(title.InnerText);
 }

Use this simple extension method to iterate through XmlNodeList:

public static void ForEachXml<TXmlNode>(this XmlNodeList nodeList, Action<TXmlNode> action)
{
    foreach (TXmlNode node in nodeList) action(node);
}

Method Call:

xDoc.GetElementsByTagName("text").ForEachXML<XmlNode>(tweet => 
    {
        if (tweet.InnerText.Length > 0)
            MessageBox.Show(tweet.InnerText);
    });

Related