C# · 12月 25, 2021

如何在C#中从plist(xml)读取键值

我只想获得softwareVersionBundleId&的字符串.捆绑版本密钥
我怎样才能将它存储到字典中以便我能够轻松搞定? <?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>

我尝试了以下代码.

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

它抛出对象引用异常.

解决方法 <键>以及< string>或< true />不是属性,它们是< dict>的子元素.通过接近配对.要构建字典,您需要将它们压缩在一起,如下所示: 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);

结果是一个字典包含:

06001