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

I just want to get a string for softwareVersionBundleId and bind version keys, how can I store it in a dictionary so that I can easily get it?

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

This is an exception to an object reference.

+5
source share
2 answers

<key> along with <string> or <true/> are not attributes; they are child <dict> elements that are related to proximity. To create a dictionary, you need to zip them up, for example:

  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 as a result, there is a dictionary containing:

 { "genre": "Application", "bundleVersion": "2.0.1", "itemName": "AppName", "kind": "software", "playlistName": "AppName", "softwareIconNeedsShine": "", "softwareVersionBundleId": "com.company.appname" } 
+5
source

IN

there is a mistake.
 a.Attribute("key").Value 

Because there is no attribute. You should use the Name and Value property instead of the 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); 
+1
source

All Articles