Ok, I\'ve got the following XML tree
1000
After parsing the XML to an XDocument, which I assume you've already been able to do, use the methods below. Note that the GetPath()
implementation is fairly naiive. See this answer for a better implementation.
public Dictionary GetLeaves(XDocument doc)
{
var dict = doc
.Descendants()
.Where(e => !e.HasElements)
.ToDictionary(e => GetPath(e), e.Value);
return dict;
}
private string GetPath(XElement element)
{
var nodes = new List();
var node = element;
while (node != null)
{
nodes.Add(node.Name.ToString());
node = node.Parent;
}
return string.Join("/", Enumerable.Reverse(nodes));
}