开发者

C# linq-to-xml, Getting a list with nodes?

This is the test xml that i am using:

<categories>
<category id="1" name="Test1">
    <category id="2" name="Test2">
        <misc id="1">&开发者_StackOverflow社区lt;/misc>
    </category>
</category>    
<category id="3" name="Test3">
    <misc id="2"></misc>
</category>    

Now i want to bind that to an ASPX treeview, i want only the elements that have the name category and i want the name of those to appear in the treeview.

Its easy to get the id and names:

var d = from t in data.Descendants("category") 
   select new { ID = t.Attribute("id").Value, Name = t.Attribute("name").Value };

but how do i keep the structure in the treeview?

This should look like this:

Test1

-> Test2

Test3


Maybe something like this if I understand you correctly? (I have not tested it)

class Category
{
    public string ID { get; set; }
    public string Name { get; set; }
    public IEnumerable<Category> SubCategories { get; set; }
}

IEnumerable<Category> CategoryTreeStructure(XElement e)
{
   var d = from t in e.Elements("category")
           select new Category()
           { 
               ID = t.Attribute("id").Value, 
               Name = t.Attribute("name").Value,
               SubCategories = CategoryTreeStructure(t)
           };

   return d;
}

Call it with:

var structure = CategoryTreeStructure(doc.Root);

"i want only the elements that have the name category" - I do not understand what you mean here? But if you only want to select those elements which have a "name" attribute then this should work:

   ...
   var d = from t in e.Elements("category")
           where t.Attribute("name") != null
           select new Category()
           ...

I understand that the upper (the "name" attribute part) is not what you wanted but I leave it there. I have tested the code against:

XDocument doc = XDocument.Parse(@"<categories>
<category id=""1"" name=""Test1"">
    <category id=""2"" name=""Test2"">
        <misc id=""1""></misc>
    </category>
</category>    
<category id=""3"" name=""Test3"">
    <misc id=""2""></misc>
</category>  
</categories>");
            var structure = CategoryTreeStructure(doc.Root);


Actually, I have found this link which does exactly what you are asking for :) And it is without LINQ, so I thought it deserved another answer.

http://www.15seconds.com/issue/041117.htm

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜