读取XML,将其保存到具有多个值的字典中

时间:2013-10-07 14:00:29

标签: c# xml dictionary

好的,所以我有以下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;
    });

2 个答案:

答案 0 :(得分:1)

真的,你使用DataTable,你也可以使用匿名类型:

XElement root = XElement.Parse(strSerializedoutput);
var list = root.Descendants("item")
    .ToDictionary(x => (int)x.Attribute("id"), x =>
    {
        var parentId = (int)x.Parent.Attribute("id");
        var level = (int)x.Parent.Attribute("level");

        return new { ParentID = parentId, Level = level };
    });

例如,当您最终写入数据库时​​,您将使用list.ParentIDlist.Level

答案 1 :(得分:0)

SELECT  y.targetelement, y.[Columns], y.[ColumnsAsXml],
        y.ColumnsAsXml.value('(item/text())[1]','NVARCHAR(100)') AS COLUMN_1,
        y.ColumnsAsXml.value('(item/text())[2]','NVARCHAR(100)') AS COLUMN_2,
        y.ColumnsAsXml.value('(item/text())[3]','NVARCHAR(100)') AS COLUMN_3,
        y.ColumnsAsXml.value('(item/text())[4]','NVARCHAR(100)') AS COLUMN_4
FROM
(
    SELECT  x.*, CONVERT(XML, N'<item>' + REPLACE(x.[Columns], N'->', N'</item> <item>') + N'</item>') AS ColumnsAsXml
    FROM    
    (
        SELECT 'TEST1', NULL UNION ALL
        SELECT 'TEST2', NULL UNION ALL
        SELECT 'TEST3', 'TEST2->TEST3' UNION ALL
        SELECT 'TEST4', 'TEST2->TEST4' UNION ALL
        SELECT 'TEST7', 'TEST2->TEST7' UNION ALL
        SELECT 'TEST6', 'TEST2->TEST4->TEST5->TEST6' UNION ALL
        SELECT 'TEST5', 'TEST2->TEST4->TEST5'   
    ) x(targetelement, [Columns])
) y