如何在c#中从plist (xml)中读取键值
本文关键字:xml 读取 键值 plist 中从 | 更新日期: 2023-09-27 17:53:05
我只是想获得字符串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);
}
抛出对象引用异常
<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
因为没有属性。您应该使用名称和值属性而不是属性
更多细节可以查看: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);