如何将.plist xml字符串转换为NSDictionary

时间:2016-12-07 08:45:54

标签: ios swift nsdictionary nsdata

我用p7b.plist下载了Swift个文件,我想读取.plist文件的值。

Alamofire

我必须包含我下载的.plist文件的对象:

  • plistData:下载的数据对象
  • plistXml:plistData
  • 中的String对象

使用这些对象中的任何一个,我想将plist fie转换为NSDictionary或Dictionary。

3 个答案:

答案 0 :(得分:4)

您可以使用Foundation框架中的PropertyListSerialization创建NSDictionary 从给定的属性列表数据。 Swift 3示例:

do {
    if let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)
        as? NSDictionary  {
            // Successfully read property list.
            print(plist)

    } else {
        print("not a dictionary")
    }
} catch let error {
    print("not a plist:", error.localizedDescription)
}

并且

    if let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)
        as? [String: Any]  { ... }

你会得到一个Swift Dictionary的结果。

答案 1 :(得分:0)

  1. 使用SWXMLHash
  2. 使用该文档逐步阅读plistXml并解析xml。
  3. 将您想要在plistXml中的元素保存到Dictionary
  4. 祝你好运!

答案 2 :(得分:-1)

这是代码的Objective-C版本。你可以很容易地转换它。

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"register.plist"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        plistPath = [[NSBundle mainBundle] pathForResource:@"register" ofType:@"plist"];
    }

    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
相关问题