0

Link posted as duplicate wasn't really helpful in my case: this answer however was Read a XML tree structure recursively in a List<T> with children lists<T>

Also, I did mention I did not know the keywords for my question, being recurssion, so I couldn't find the proper answer at the time.

In this XML sample below we have one entry. An entry can contain another entry, this entry can contain yet another entry and so on.

<entry name="sales" label="Sales">
      <entry name="discounts" label="Discounts" entity="sales_discount" />
      <entry name="discount_add" label="New Discount" entity="sales_discount" view="add" />
      <entry name="users" label="Users" entity="sys_user" />
</entry>

the equivalent in c#

public interface IMenuEntry
{
    string Name { get; set; }
    string Label { get; set; }
    IEntity Entity { get; set; }
    ViewType View { get; set; }
    IEnumerable<IMenuEntry> MenuEntries { get; set; }
}

I know how to load and save xml into .net and back.

My problem lies within the implementation. If we knew before hand that one entry can only contain one other entry, one would do a simple for each loop.

var entries = new List<MenuEntry>();    
foreach (var xMainEntry in xMainEntries)
{
    var xMainEntryName = xMainEntry.Attribute("name").Value;
    var xMainEntryLabel = xMainEntry.Attribute("label").Value;
    var mainEntry = new MenuEntry() { Label = xMainEntryLabel, Name = xMainEntryName};             
}

However, I do not know the amount of childelements of the same type, so I do not know before hand how many times I would have to do xMenu.Elements("entry").Elements("entry).Elements("entry") , how could I keep on looping through these elements and build up the structure with the same amount of levels in c# (obviously I will need this the other way around to save the object to xml as well. But I figure, if I know how to do it one way, I can do it the other way around as well

Community
  • 1
  • 1
Hairydruidy
  • 107
  • 2
  • 11
  • Just to clarify, the main issue is that `/IMenuEntry`s can be nested in a tree format, right? This might be something C#'s automatic XML serialization would do pretty easily; or you might be able to use a recursive function. – Katana314 Mar 11 '16 at 14:11
  • This is a job for **recursion**. – Joel Coehoorn Mar 11 '16 at 14:27
  • Ok thanks. next time you may want to leave what i posted as is... rather than deleting my apology ;) I did apologize beforehand if this question was asked before... i usualy find my way around I just didnt know what to look for... now I do. Thanks – Hairydruidy Mar 11 '16 at 22:30
  • FYI, for anyone looking for the same thing in the furture: this answer was way more helpfull: http://stackoverflow.com/questions/6164241/read-a-xml-tree-structure-recursively-in-a-listt-with-children-listst – Hairydruidy Mar 14 '16 at 08:36

0 Answers0