将XML转换为字典

时间:2013-10-07 15:33:01

标签: c# xml linq

我正在转换这个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>

使用此字典进入字典:

XElement root = XElement.Parse(strSerializedoutput);
Dictionary<int, Pair> list = root.Descendants("item").ToDictionary(x => (int)x.Attribute("id"), x =>
{
    var pId = x.Parent.Attribute("id");
    var depthLevel = x.Attribute("level");
    if (pId == null)
    {
        return new { parentID = 0, level = (int)depthLevel };
    }
    else
    {
        return new { parentID = (int)pId, level = (int)depthLevel };
    }
});

其中对是:

    public class Pair
    {
        int parentID;
        int level;
    }

我希望成为:

ID | ParentID  | level
------------------------
1     NULL         1
2     NULL         1
3      2           2
4      2           2
5      4           3
6      5           4
7      2           2

但我收到错误

错误35无法隐式转换类型  'System.Collections.Generic.Dictionary int,AnonymousType#1'到'System.Collections.Generic.Dictionary int,ProposalSystem.handlers.main.Pair'

2 个答案:

答案 0 :(得分:2)

XElement root = XElement.Parse(strSerializedoutput);
Dictionary<int, Pair> list = root.Descendants("item")
                                 .ToDictionary(x => (int) x.Attribute("id"),
                                  x => {
                            var pId = x.Parent.Attribute("id");
                            var depthLevel = x.Attribute("level");
                            return pId == null ? new Pair { parentID = 0, level = (int)depthLevel } :
                            new Pair { parentID = (int)pId, level = (int)depthLevel };
                          });

public class Pair
{
    public int parentID;
    public int level;
}

答案 1 :(得分:2)

您的词典类型为:

Dictionary<int, Pair>

然而,对于元素类型,您不会返回Pair,而是返回此匿名类型:

return new { parentID = 0, level = (int)depthLevel };