【问题标题】:Parsing Dictionary within a Dictionary在字典中解析字典
【发布时间】:2014-03-30 12:11:05
【问题描述】:

我有这个 xml:

<plist version="1.0">
<dict>
    <key>Johnson</key>
    <dict>
        <key>id</key>
        <string>4525434</string>
        <key>name</key>
        <string>Neil Johnson</string>
        <key>firstname</key>
        <string>neil</string>
        </dict>
    <key>Adam</key>
    <dict>
        <key>id</key>
        <string>481689</string>
        <key>name</key>
        <string>Andrew Adam</string>
        </dict>
</dict>

如何解析这个并根据键Johnson and Adam显示数据

我试过了:

var xmlDict = doc.Root.Element("dict");
Dictionary<string, string> dict = xmlDict.Elements("key")
           .Zip(xmlDict.Elements("string"), (k, s) => new KeyValuePair<string, string>(k.Value, s.Value))
           .ToDictionary(x => x.Key, x => x.Value);

但这只会将项目添加到内部字典中。

【问题讨论】:

    标签: c# dictionary xml-parsing linq-to-xml


    【解决方案1】:

    您的数据是嵌套的,因此您需要Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt; 来存储它。以下查询应该可以解决问题:

    var dict = xmlDict.Elements("key")
               .Zip(xmlDict.Elements("dict"), (k, v) => new { k, v })
               .ToDictionary(
                    x => (string)x.k,
                    x => x.v.Elements("key")
                            .Zip(x.v.Elements("string"), (k, v) => new { k, v })
                            .ToDictionary(y => (string)y.k, y => (string)y.v));
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2016-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多