I just want to get string for softwareVersionBundleId & bundle version keys how can i store it into dictionary so that i can able to get easily?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>genre</key>
    <string>Application</string>
    <key>bundleVersion</key>
    <string>2.0.1</string>
    <key>itemName</key>
    <string>AppName</string>
    <key>kind</key>
    <string>software</string>
    <key>playlistName</key>
    <string>AppName</string>
    <key>softwareIconNeedsShine</key>
    <true/>
    <key>softwareVersionBundleId</key>
    <string>com.company.appname</string>
</dict>
</plist>
i tried the following code.
            XDocument docs = XDocument.Load(newFilePath);
            var elements = docs.Descendants("dict");
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            foreach(var a in elements)
            {
               string key= a.Attribute("key").Value.ToString();
               string value=a.Attribute("string").Value.ToString();
                keyValues.Add(key,value); 
            }
It is throwing object reference exception.
<key> along with <string> or <true/> aren't attributes, they are child elements of <dict> that are paired by proximity.  To build your dictionary, you need to zip them together, like so:
        var keyValues = docs.Descendants("dict")
            .SelectMany(d => d.Elements("key").Zip(d.Elements().Where(e => e.Name != "key"), (k, v) => new { Key = k, Value = v }))
            .ToDictionary(i => i.Key.Value, i => i.Value.Value);
And the result is a dictionary containing:
{ "genre": "Application", "bundleVersion": "2.0.1", "itemName": "AppName", "kind": "software", "playlistName": "AppName", "softwareIconNeedsShine": "", "softwareVersionBundleId": "com.company.appname" }
There is an error in
a.Attribute("key").Value
Cause there is no attribute. You should use Name and Value property instead of attribute
More details you can check: XMLElement
foreach(var a in elements)
{
    var key= a.Name;
    var value = a.Value;
    keyValues.Add(key,value); 
}
There is another way for this approach
var keyValues = elements.ToDictionary(elm => elm.Name, elm => elm.Value);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With