我有一个层次结构的表。像这样:
(来源:aspalliance.com)
和此处显示的表格数据:
(来源:aspalliance.com)
这种策略使我能够拥有无限的类别和子类别。
我使用 ASP.net 3.5 SP1 和 LINQ 和 MSSQL Server2005。 如何将其转换为 XML?我可以使用数据集对象 和“.GetXML()”方法来完成。但是如何用 LINQtoSQL 或 LINQtoXML 实现它???或者是否有另一种更简单的方法来执行该操作?你的建议是什么?最好的办法?我在网上搜索但没有找到 .net 3.5 功能。
问题更新
感谢 Murph,但现在我遇到了一个新问题。我想在我的项目中制作一个 Dunamic SiteMap 文件。你知道 ASP.net 中的 SiteMap 文件是这样的:
<siteMapNode url="~/Category?cid=0" title="Home" description="Home">
<siteMapNode url="~/Category?cid=1" title="a" description="" />
<siteMapNode url="~/Category?cid=2" title="b" description="" >
<siteMapNode url="~/Category?cid=3" title="c" description="" />
<siteMapNode url="~/Category?cid=4" title="d" description="" />
</siteMapNode>
</siteMapNode>
主要问题是,根据 Mr.Murph 的代码,子类别将嵌套在元素中。但在 SiteMap 案例中,我们没有这样的元素,所有类别和子类别都嵌套在元素中。我怎样才能更改 Mr.Murph 代码来塑造这个架构?
最佳答案
非常快(并且完全未经测试)。
使用 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 数据上下文,其中您已将表映射到 Menus,并且父/子关系是父端的 ChildMenus。
- 我们创建一个新文档
- 我们创建一个新元素,我们将其用作我们称之为 menuxml 的根
- 然后,我们执行一个 linq to SQL 查询以选择所有没有父项的菜单条目,并调用 GetMenuXML 为这些条目的单个菜单记录(即该记录及其子项)输出 XML。<
- GetMenuXML 输出单个菜单条目,在属性和元素之间拆分,唯一略有不同的是我使用了 lamba 表达式而不是冗长的语法来生成子菜单 - 但如果我做对了(记住没有测试!)那是在做一些事情
从 menu.ChildMenus 中的 m 选择 GetMenuXML(m)
如果它有效(!)你应该得到类似于 XML 的东西
<menuxml>
<menu MenuID="1" Text="Product">
<Description>A list of products</Description>
<menus>
<menu MenuID="6" Text="Background">
<Description>Product Background</Description>
<menus>
<menu MenuID="18" Text="Internet Restriction">
<Description>Internet Restriction</Description>
<!-- children if any would be here -->
</menu>
<menu MenuID="19" Text="Speed Solution">
<Description>Speed Solutions</Description>
</menu>
</menus>
</menu>
<menu MenuID="7" Text="Background">
<Description>Product Details</Description>
</menu>
</menus>
</menu>
<!-- rest of the top level menus -->
</menuxml>
关于c# - 如何使用 ASP.net 3.5 和 LINQ 将数据库分层数据转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2824794/