Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read key value from plist (xml) in C#

Tags:

c#

dictionary

xml

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.

like image 622
Manikandan Selvanathan Avatar asked Jun 04 '15 03:06

Manikandan Selvanathan


2 Answers

<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"
}
like image 189
dbc Avatar answered Nov 07 '22 16:11

dbc


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);
like image 2
Peyman Avatar answered Nov 07 '22 17:11

Peyman