user2056563
user2056563

Reputation: 640

Parsing Dictionary within a Dictionary

i have this 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>

How to parse this and display the data based on key Johnson and Adam

I tried this:

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);

But this will only add the items to inner Dictionary.

Upvotes: 1

Views: 87

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Your data is nested, so you need Dictionary<string, Dictionary<string, string>> to store it. Following query should do the trick:

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));

Upvotes: 3

Related Questions