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

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

    The challenge would be to write it as 1 LINQ query, but that's beyond me. LINQ isn't easy/suitable for recursion.

    I'll sketch a solution, I'm not going to write it out :

    • read the Xml into an XDocument (or XmlDocument)
    • define a class Unit { ... ; ... List Children; }
    • define Units and Root classes if desired. I'll flatten that part here
    • get a flat list of all Unit tags, var units = doc.Descendants("Unit");
    • Iterate over those elements, I assume that a parent node will always come before a nested Unit
    • look up the Parent of each node in a var Lookup = new Dictionary ();
    • if a Parent is found, add the current node (new Unit) to its Children
    • else add it to a topList
    • add the new Unit and the XElement to the dictionary.
    • the lookup dictionary is only needed while creating the lists.

提交回复
热议问题