开发者

Generate hierarchical XML with Linq

I have the following class that is supposed to represent a hierarchical data structure

class Person
{
   int Id { get; set; }
   Person Parent { get; set; }
   List<Person> Children { get; set; }
}

In my UI I receive a collection of Person where each one may have children. I need to print out an XML with the following structure:

<root>
   <Person id="1" parent_id="0" name="">
      <Person id="5" parent_id="1" name="">
         <Person id="10" parent_id="5" name="">
         </Person>
      </Person>
      <Person id="6" parent_id="1" name="">
      </Person>
   </Person>
   <Person id="2" parent_id="0" name="">
   </Person>
</root>

Right now I wrote this but my code is not recursive. Can you help me on getting this done using LINQ?

    public XDocument GetHtmlWorkbookTree(List<Person> persons)
    {
        var document = new XDocument();
        var root = new XElement("Person",
            persons.Select(
            r => new XEle开发者_StackOverflow中文版ment("Person",
                new XAttribute("id", r.Id))));
        document.Add(root);
        return document;
    }


It's not that big a deal, it's the same as any recursion. Just pass on the XElement to the recursive function.

I'm thinking something like this:

public XDocument GetHtmlWorkbookTree(List<Person> persons)
    {
        var document = new XDocument();
        Person rootperson = persons.SingleOrDefault( ... select the person that you want to start with ... );
        var root = new XElement("Person", ... fill with attributes as you like ...);
        document.Add(root);

        foreach(var item in rootperson.Children)
        {
             AddChildRecursive(root, rootperson);
        }

        return document;
    }

public void AddChildRecursive(XElement element, Person person)
{
    foreach(var item in person.Children)
    {
        XElement newchild = new Element("Person", ... fill with attributes as you like ...);
        element.Add(newchild);
        AddChildRecursive(newchild, item);
    }
}

I'm not sure that this will work as it is, since I don't have VS right now to test it, but I hope you get the idea!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜