views:

69

answers:

1

I am trying to use XML created from a lookup list in SharePoint as a datasource for a treeview. It is in the form of :

<NewDataSet>
  <test_data>
    <ID>1</ID>
    <Title>MenuItem_1</Title>
    <child_of />    
  </test_data>
  <test_data>
    <ID>2</ID>
    <Title>Subitem_1</Title>
    <Action>http://www.google.com&lt;/Action&gt;
    <child_of>MenuItem_1</child_of>   
  </test_data>
  <test_data>
    <ID>3</ID>
    <Title>Subitem_2</Title>
    <Action>http://www.google.com&lt;/Action&gt;
    <child_of>MenuItem_1</child_of>
  </test_data>
  <test_data>
    <ID>4</ID>
    <Title>MenuItem_2</Title>
    <child_of />
  </test_data>
  <test_data>
    <ID>5</ID>
    <Title>Subitem_2_1</Title>
    <Action>http://www.google.com&lt;/Action&gt;
    <child_of>MenuItem_2</child_of>
  </test_data>
  <test_data>
    <ID>6</ID>
    <Title>Subitem_2_2</Title>
    <Action>http://www.google.com&lt;/Action&gt;
    <child_of>MenuItem_2</child_of>
  </test_data>
  <test_data>
    <ID>7</ID>
    <Title>Subitem_2_2_1</Title>
    <Action>http://www.google.com&lt;/Action&gt;
    <child_of>Subitem_2_2</child_of>
  </test_data>
</NewDataSet>

There may be N tiers, but the items relate to the parent via the <child_of> element. I can't seem to figure out how to write the LINQ in C# to nest the menu items properly. A friend recommended I post here. Any help is greatly appreciated.

A: 

You could do something like this, but I would think long about actually putting it into production code.

from n in testData.Elements("test_data")
                  .Aggregate(new Dictionary<string, TreeNode<string>>() 
                        {{ string.Empty, new TreeNode<string>() }},
                        (d, e) =>
                        {
                            var curNode = new TreeNode<string>(e.Element("ID").Value);
                            d.Add(e.Element("Title").Value, curNode);
                            d[e.Element("child_of").Value].AddChild(curNode);
                            return d;
                        })
                  .Values
where n.Parent == null
select n;

Note that this assumes that an element has a parent key of "empty string" or comes in the source list after its parent.

Personally, I would factor this (especially the aggregation) into a method of its own.

Gideon Engelberth