Florian Florian - 1 month ago 7
C# Question

How to filter on a xml node name keeping the tree structure?

I want to retrieve a tree structure (or a node structure) from a xml file, ignoring some element. In the example I just want to get the Folder nodes.

<Folder name="users">
<Folder name="user1">
<File name="file1.txt"></File>
<Folder name="mydocuments">...</Folder>
</Folder>
</Folder>
<Folder name="windows"></Folder>
<Folder name="temp"></Folder>


But I want to keep the "tree" of the folder nodes and note lose it using a method like :

var folders = doc.Descendants().Where(n => n.Name == "Folder");


I want get something like this :

Folder (users)
|
|__ Folder (user1)
|
|__ Folder (mydocuments)
Folder (windows)
Folder (temp)


How is it possible using Linq To Xml ?

Answer

You could just remove the files from the folders:

doc.Descendants("File").Remove();