I have an XML file as following:
<?xml version="1.0" encoding="utf-8"?>
<files>
<file name="1">
<file name="4">
<file name="9">
</file>
</file>
</file>
<file name="2">
</file>
<file name="3">
<file name="5">
<file name="7">
</file>
</file>
<file name="6">
</file>
</file>
</files>
I want to create an id for each node using the level of each.
1
1,4
1,4,9
2
3
3,5
3,5,7
3,6
an save it as a list. For each parent will be an entry in the list as:
0
1
1,4
1,4,9
1
2
2
3
3,5
3,5,7
3,6
I used the following code:
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
var doc = XDocument.Load("test2.xml");
var hierarchy = doc.Descendants("file")
.Where(x => x.Element("file") == null)
.Select(x => x.AncestorsAndSelf("file")
.Reverse()
.Select(f => (int)f.Attribute("name"))
.ToList());
var step = hierarchy.Select(a => String.Join(", ", a));
}
}
This function may be called the flattening a nested nodes/children in XML file. This code generates a list of only the last nodes and that is it(see the output).
1,4,9
2
3,5,7
3,6
But I rather prefer to have an address/id for each node separately.