Having trouble populating listbox from xml elements

The XML is as followed:

<?xml version="1.0" encoding="utf-8"?>
<Folder_Settings>
  <Documents>Checked</Documents>
  <Pictures>Not Checked</Pictures>
  <Music>Checked</Music>
  <Videos>Not Checked</Videos>
  <Downloads>Checked</Downloads>
  <Contacts>Checked</Contacts>
  <Favorites>Not Checked</Favorites>
  <Other>Checked</Other>
  <OtherFolderSettings>C:\Users\Asus\Desktop\revouninstaller-portable</OtherFolderSettings>
  <OtherFolderSettings>D:\Personal Website</OtherFolderSettings>
  <OtherFolderSettings>D:\testing</OtherFolderSettings>
  <OtherFolderSettings>C:\Users\Asus\Desktop\revouninstaller-portable</OtherFolderSettings>
  <OtherFolderSettings>C:\Users\Asus\.eclipse</OtherFolderSettings>
</Folder_Settings>

I would like to take the information inside of OtherFolderSettings and populate it into a listbox. The code I am using sort of works, but it only adds the first two folders strings into the listbox. Thank you in advance for all help and advice.

Code:

 var applicationSettingsXML = new XmlDocument();
            var XMLFileStream = new FileStream("Settings.xml", FileMode.Open);
            applicationSettingsXML.Load(XMLFileStream);

            var folderList = applicationSettingsXML.GetElementsByTagName("Folder_Settings");
            for (var i = 0; i <= folderList.Count; i++)
            {

                listBox1.Items.Add( applicationSettingsXML.GetElementsByTagName("OtherFolderSettings")[i].InnerText);

            }

            XMLFileStream.Close();
Jon Skeet
people
quotationmark

The reason your code isn't working is because your loop is:

for (var i = 0; i <= folderList.Count; i++)

... where folderList is the list of Folder_Settings elements. There's only one of those, so you're iterating twice. It's a good job you don't actually use folderList[i], because otherwise you'd be out of bounds on the second iteration. Loops like that should pretty much always use < rather than <=.

However, I would strongly recommend using LINQ to XML instead of XmlDocument - it makes everything much simpler. I'd also recommend using foreach loops whenever you can, too:

var doc = XDocument.Load("Settings.xml");
foreach (var element in doc.Root.Elements("OtherFolderSettings))
{
    listBox1.Items.Add(element.Value);
}

(Oh, and use using statements to close resources cleanly...)

people

See more on this question at Stackoverflow