Using Linq To XML, method to get path to all leaves?

前端 未结 2 1102
北海茫月
北海茫月 2020-12-18 06:40

Ok, I\'ve got the following XML tree


    
        
            1000

        
相关标签:
2条回答
  • 2020-12-18 07:23

    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<string, string> 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<string>();
        var node = element;
        while (node != null)
        {
            nodes.Add(node.Name.ToString());
            node = node.Parent;
        }
    
        return string.Join("/", Enumerable.Reverse(nodes));
    }
    
    0 讨论(0)
  • 2020-12-18 07:38

    You can find the leaves by looking for elements that have no descendants:

    var doc = XDocument.Load(fileName);
    var leaves = 
        from e in doc.Descendants()
        where !e.Elements().Any()
        select e;
    

    I don't know if there is a built-in way to get the path of an element, but you can easily create an extension method to build it:

    static class Extensions
    {
        public static string Path(this XElement element)
        {
            XElement tmp = element;
            string path = string.Empty;
            while (tmp != null)
            {
                path = "/" + tmp.Name + path;
                tmp = tmp.Parent;
            }
            return path;
        }
    }
    

    You can then build the dictionary like this:

    var dict = leaves.ToDictionary(e => e.Path(), e => e.Value);
    
    0 讨论(0)
提交回复
热议问题