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

前端 未结 4 821
孤独总比滥情好
孤独总比滥情好 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:51

    class Unit
    {
        public string Name;
        public List Children;
    
        public Unit(string name, List children)
        {
            Name = name;
            Children = children;
        }
    
        public static Unit Convert(XElement elem)
        {
            return new Unit(elem.Attribute("Name").Value, Convert(elem.Elements()));
        }
    
        public static List Convert(IEnumerable elems)
        {
            return elems.Select(Unit.Convert).ToList();
        }
    }
    

    You can use it like this:

    Unit.Convert(XDocument.Parse(xml).Root.Elements())
    

提交回复
热议问题