You just need a class that will store the data of a Folder
node of the XML.
Like this one:
public class Folder
{
/// <summary>
/// List of folders in the folder
/// </summary>
[XmlElement(ElementName = "Folder")]
public List<Folder> Folders { get; set; }
/// <summary>
/// Name of the folder
/// </summary>
[XmlAttribute("name")]
public string Name { get; set; }
/// <summary>
/// Access information of the folder
/// </summary>
[XmlAttribute("access")]
public string Access { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
ToString(sb, 0);
return sb.ToString();
}
private void ToString(StringBuilder sb, int level)
{
const int indent = 2;
sb.Append(new string(' ', level * indent));
sb.AppendLine($"{Name} ({Access})");
foreach (var folder in Folders)
folder.ToString(sb, level + 1);
}
}
An other for the container:
public class Container
{
/// <summary>
/// List of folders in the container
/// </summary>
[XmlElement(ElementName = "Folder")]
public List<Folder> Folders { get; set; }
/// <summary>
/// Revision of the container
/// </summary>
[XmlAttribute("rev")]
public string Revision { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine($"Container rev: {Revision}");
foreach (var folder in Folders)
sb.AppendLine(folder.ToString());
return sb.ToString();
}
}
Use a XmlSerializer to de-serialize the file. To manage the container
root node, use XmlRootAttribute
as explained here.
Here the resulting program:
class Program
{
static void Main(string[] args)
{
var rootAttribute = new XmlRootAttribute { ElementName = "container", IsNullable = true };
var serializer = new XmlSerializer(typeof(Container), rootAttribute);
using (var reader = new StreamReader("./input.xml"))
{
var result = (Container)serializer.Deserialize(reader);
Console.WriteLine(result);
}
}
}
With this content in input.xml
:
<container rev="1">
<Folder name="root" access="all">
<Folder name="aaa" access="user1">
<Folder name="aab" access="user2" />
<Folder name="aac" access="user2"/>
</Folder>
<Folder name="bbb" access="user2" />
<Folder name="ccc" access="user1"/>
</Folder>
</container>
The output is:
Container rev: 1
root (all)
aaa (user1)
aab (user2)
aac (user2)
bbb (user2)
ccc (user1)