【发布时间】:2013-10-07 14:00:28
【问题描述】:
好的,所以我有以下 XML:
<root>
<item id="1" level="1" />
<item id="2" level="1">
<item id="3" level="2"/>
<item id="4" level="2">
<item id="5" level="3">
<item id="6" level="4" />
</item>
</item>
<item id="7" level="2" />
</item>
</root>
我希望字典输出是这样的,这样我就可以将数据插入到我的 sql 数据库中,
ID | ParentID | level
------------------------
1 NULL 1
2 NULL 1
3 2 2
4 2 2
5 4 3
6 5 4
7 2 2
目前这是我获取前 2 列的代码,但不确定如何让第 3 列“级别”显示在我的字典中。
XElement root = XElement.Parse(strSerializedoutput);
Dictionary<int, int> list = root.Descendants("item").ToDictionary(x => (int)x.Attribute("id"), x =>
{
var parentId = x.Parent.Attribute("id");
if (parentId == null)
return 0;
return (int)parentId;
});
【问题讨论】:
-
使用
DataTable(msdn.microsoft.com/en-us/library/system.data.datatable.aspx) 而不是字典。 -
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# xml dictionary