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

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

    Why don't you implement a Tree for storing units. That would be much easier and natural than Lists.

    Have a look at this comment for a good implementation using LinkedList.

    See

    • MSDN: Algorithms and Data Structures
    • Tree data structure in C#
    • Tree: Implementing a Non-Binary Tree in C#

    If you HAVE to use List, then you may use recursion to build it. I'm assuming your Unit has a property (IList Unit.ChildUnits) to hold all children List. If not you may want to wrap Unit into another class that has this.

    public List LoadAllUnits(XMLNode rootNode){
        List allUnits = new List();
        foreach(var childNode in rootNode.ChildNodes){
            allUnits.Add(LoadAllSubUnits(childNode);
        }
        return allUnits;
    }
    
    
    private Unit LoadAllSubUnits(XMLNode node){
        Unit u = GetUnitFromCurrentNode(node); // Converts current node into Unit object
        if(root.HasChildNode){
             foreach(var childNode in node.ChildNodes){
                 u.ChildUnits.Add(LoadAllSubUnits(childNode);
             }
        }
        return u;
    }
    

提交回复
热议问题