如何使用ASP.net 3.5和LINQ将数据库分层数据转换为XML

我有一个分层结构的表。 像这样:
替代文字http://aspalliance.com/ArticleFiles/822/image002.gif

和表数据显示在这里:
替代文字http://aspalliance.com/ArticleFiles/822/image003.gif
这种策略使我能够拥有无限的类别和子类别。

我使用ASP.net 3.5 SP1和LINQ和MSSQL Server2005。 如何将其转换为XML? 我可以使用数据集对象和“ .GetXML() ”方法。 但是如何用LINQtoSQL或LINQtoXML实现呢??? 或者如果有另一种更简单的方法来执行该操作? 你的建议是什么? 最好的方法? 我在网上搜索但没有找到.net 3.5 featuers。

问题更新
对墨菲有所了解,但现在我遇到了一个新问题。 我想在我的项目中创建一个Dunamic SiteMap文件。 您知道ASP.net中的SiteMap文件如下所示:

       

主要问题是,根据Mr.Murph’s Code,子类别将嵌套在元素中。 但在SiteMap案例中,我们没有这样的元素,所有类别和子类都嵌套在元素中。 我怎样才能改变Mr.Murph代码来塑造这个Schema?

好的很快(并且彻底未经测试)。

使用Linq to SQL和Linq to XML(它们是通用的.NET而不是ASP.NET特定的)“滚动你自己的”XML非常简单,这应该足够了,我将详细介绍一些假设(现在略微修改为建议):

 void Main() { DataContext dc = new DataContext(); menuXML = new XDocument(); XElement root = new XElement("menuxml", from m in dc.Menus where m.ParentID == null select GetMenuXML(m)); menuXML.Add(root); // You've now got an XML document that you can do with as you need // For test you can save... menuXML.Save("filename.xml"); } private static XElement GetMenuXML(Menu menu) { return new XElement("category", new XAttribute("MenuID", menu.MenuID), new XAttribute("Text", menu.Text), new XElement("Description", menu.Description), new XElement("menus", menu.Menus.Select(m => GetMenuXML(m)))); } 

好的,从顶部

  • 我假设一个名为DataContext的Linq to SQL数据上下文,其中您已将表映射到菜单,并且父/子关系是父端的ChildMenus。
  • 我们创建一个新文档
  • 我们创建了一个新元素,我们将其用作我们称之为menuxml的根
  • 然后,我们执行linq to SQL查询以选择所有没有父项的菜单项,并调用GetMenuXML以输出这些条目的单个菜单记录(即该记录及其子项)的XML。
  • GetMenuXML在属性和元素之间输出单个菜单条目,唯一不同的是我使用了lamba表达式而不是用于生成子菜单的详细语法 – 但是如果我做得对(请记住没有测试!)多数民众赞成在做一些事情

from m in menu.ChildMenus select GetMenuXML(m)

如果它工作(!)你应该得到类似的XML

   A list of products   Product Background   Internet Restriction    Speed Solutions     Product Details      

谢谢亲爱的墨菲。 我使用了你的代码,效果很好。 但正如你所说,你没有测试你的代码,所以GetMenuXML()有一些错误。 这是更正:

 private static XElement GetMenuXML(Menu menu) { return new XElement("category", new XAttribute("MenuID", menu.MenuID), new XAttribute("Text", menu.Text), new XElement("Description", menu.Description), new XElement("menus", menu.Menus.Select(m => GetMenuXML(m)))); }