Read a XML tree structure recursively in a List with children lists

前端 未结 4 806
孤独总比滥情好
孤独总比滥情好 2021-02-06 03:10

I have an XML like this:

And I have a Member class with property Name.

How can I read every Unit and its children Units into multiple generic List

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 03:57

    This would do it, using plain recursion:

    public class Unit
    {
        public string Name { get; set; }
        public List Children { get; set; }
    }
    
    class Program
    {
        public static void Main()
        {
            XDocument doc = XDocument.Load("test.xml");
            List units = LoadUnits(doc.Descendants("Units").Elements("Unit"));
        }
    
        public static List LoadUnits(IEnumerable units)
        {
            return units.Select( x=> new Unit() 
                                     { Name = x.Attribute("Name").Value, 
                                       Children = LoadUnits(x.Elements("Unit")) 
                                     }).ToList();
        }
    }
    

提交回复
热议问题