Grouping XML with Linq, Hierarchy isn't right



I'm trying to work out how to create a treeview menu from a sql query in asp.net C#. As a learning exercise, I've got a database containing holidays from the past three years -- I want to create a treeview displaying the holidays sorted by year. For example, "Year --> Holiday Name --> Holiday Date", where "-->" denotes a hierarchical level.


Anyway, I'm getting my holidays returned as an XML doc from SQL using this query:



SELECT [Year], [Holiday], [Date] FROM [Database] FOR XML PATH('Holiday'), ROOT('Holidays')


This, of course, returns an XML document with no grouping, so I'm using Linq to group my holidays by year while the data's coming from the database, like so:



XmlReader reader = sqlCommand.ExecuteXmlReader();

if (reader.Read())
{
XElement doc = XElement.Load(reader);
var newData =
new XElement("Holidays",
from data in doc.Elements("Holiday")
group data by (int)data.Element("Year") into groupedData
select new XElement("Group",
new XAttribute("ID", groupedData.Key),
from g in groupedData
select new XElement("Holiday",
g.Element("Name"),
g.Element("Date")
)
)
);


This is better: it groups my holidays by year, but my treeview ends up looking like this:



2012
Holiday
Christmas Eve
12/24/12
Holiday
Christmas Day
12/25/12
Holiday
New Year's Eve
12/31/12


... and so on. I'm new to Linq, so I'm not really sure what to do here. I want to get rid of that "Holiday" level and make the actual date a child node of the Holiday name. I can't do anything with the SQL query, since XML can only have one root node. Any ideas?


No comments:

Post a Comment