[英]How to read key value from plist (xml) in C#
我只想獲取softwareVersionBundleId和bundle版本密鑰的字符串如何將其存儲到字典中以便我能夠輕松獲得?
<?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);
}
它拋出對象引用異常。
<key>
以及<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);
結果是一個字典包含:
{ "genre": "Application", "bundleVersion": "2.0.1", "itemName": "AppName", "kind": "software", "playlistName": "AppName", "softwareIconNeedsShine": "", "softwareVersionBundleId": "com.company.appname" }
有一個錯誤
a.Attribute("key").Value
因為沒有屬性。 您應該使用Name和Value屬性而不是attribute
您可以查看更多詳細信息: XMLElement
foreach(var a in elements)
{
var key= a.Name;
var value = a.Value;
keyValues.Add(key,value);
}
這種方法還有另一種方法
var keyValues = elements.ToDictionary(elm => elm.Name, elm => elm.Value);
您可以嘗試這個Nuget包: https ://www.nuget.org/packages/PListDeserializer/或者git: https : //github.com/maksgithub/PListSerializer
class MyClass
{
[PlistName("genre")]
public string Genre { get; set; }
[PlistName("bundleVersion")]
public string BundleVersion { get; set; }
[PlistName("itemName")]
public string ItemName { get; set; }
[PlistName("kind")]
public string Kind { get; set; }
[PlistName("playlistName")]
public string PlaylistName { get; set; }
[PlistName("softwareIconNeedsShine")]
public bool SoftwareIconNeedsShine { get; set; }
[PlistName("softwareVersionBundleId")]
public string SoftwareVersionBundleId { get; set; }
}
var byteArray = Encoding.ASCII.GetBytes(YourPlist.plist);
var stream = new MemoryStream(byteArray);
var node = PList.Load(stream);
var deserializer = new Deserializer()
deserializer.Deserialize<MyClass>(rootNode);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.