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

时间:2015-06-04 03:20:12

标签: c# xml dictionary

我只想获取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); 
            }

抛出对象引用异常。

3 个答案:

答案 0 :(得分:7)

<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"
}

答案 1 :(得分:2)

中有错误
a.Attribute("key").Value

因为没有属性。您应该使用Name和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);

答案 2 :(得分:0)

您可以尝试使用以下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);