1

First and foremost request is that if you find this to be a duplicate request, please, guide me to the correct page.

I tried few solutions but none worked. May be I'm doing something silly. Anyway, I'm stuck with something.

Here's my XML format:

<Root>
<MainFolder Name="Main">
    <Folder Name="Folder1">
        <Folder Name="SubFolder1">
            <File />
            <Folder Name="SubFolder2">
            </Folder>
        </Folder>
    </Folder>
    <Folder Name="Folder2">
        <Folder Name="SubFolder3">
            <File />
        </Folder>
    </Folder>
</MainFolder>
</Root>

The thing is that I want to traverse through the XML and show the Name attribute value for all Folders tag.

As of now, I'm just able to search and show results for only "Folder1" and "Folder2". I'm not to traverse through subfolders.

Please, help me with this. Thanks in advance.

Sample of the code I'm using currently:

XElement root = XElement.Load("File.xml");
var mainFolder = root.Element("Main");
foreach (var folder in mainFolder.Elements("Folder"))
{
    folderName[noOfFolders] = folder.Attribute("Name").Value;
    MessageBox.Show(folderName[noOfFolders]);

    foreach (var file in folder.Elements("File"))
    {
     ...
    }

}

Please, let me know if you guys need more info.

Praveen
  • 231
  • 1
  • 4
  • 15

1 Answers1

1

Given your definition of root above, this should do it:

foreach (var folderElement in root.Descendants("Folder"))
{
    Console.WriteLine(folderElement.Attribute("Name").Value);
}

Descendants() lists all descendant elements (i.e. not just immediate) in document order.


Folder1
SubFolder1
SubFolder2
Folder2
SubFolder3
Press any key to continue . . .
Micke
  • 2,251
  • 5
  • 33
  • 48
  • 1
    Thank you. I couldn't believe it was that simple. Anyway, I'm learning something new everyday to increase my grasp on C#. This will add on for today:) – Praveen Aug 27 '15 at 09:44