简体   繁体   English

如何将这个 .plist 文件直接解析为 Swift 中的对象?

[英]How can I parse this .plist file directly to the objects in Swift?

I have aa covid.plist file like below and trying to figure out how to parse to the objects and read this data ?我有一个像下面这样的 covid.plist 文件,并试图弄清楚如何解析对象并读取这些数据?

covid.plist covid.plist

<?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>key1</key>
    <string>value for key1</string>
    <key> key2</key>
    <string>valua for key1</string>
    <key>Covid1</key>
    <dict>
        <key>covid1_key</key>
        <string>covid1_value</string>
    </dict>
    <key>Covid2</key>
    <dict>
        <key>covid2_key</key>
        <string>covid2_value</string>
    </dict>
</dict>
</plist>

Your code seems to be infected so i wear mask, wash my hand and keep my mac little distance :) Anyway I think PropertyListDecoder can be used to decode plist file directly to your objects for your case你的代码似乎被感染了,所以我戴上口罩,洗手并与我的 mac 保持一点距离 :) 无论如何,我认为PropertyListDecoder可用于将 plist 文件直接解码为你的对象的对象

struct Covid1:Codable {
    var covid1_key:String?
    private enum CodingKeys : String, CodingKey {
              case covid2_key = "covid1_key"
    }
}

struct Covid2:Codable {
    var covid2_key:String?
    private enum CodingKeys : String, CodingKey {
              case covid2_key = "covid2_key"
    }    
}

struct PlistConfiguration:Codable {
    var key1:String?
    var covid1: Covid1?
    var covid2: Covid2?
    
    private enum CodingKeys : String, CodingKey {
              case key1 = "key1"
              case covid1 = "Covid1"
              case covid2 = "Covid2"
    }
}

And use this function for action :并使用此功能进行操作:

func parseCovid() -> PlistConfiguration {
    let url = Bundle.main.url(forResource: "covid", withExtension: "plist")!
    let data = try! Data(contentsOf: url)
    let decoder = PropertyListDecoder()
    return try! decoder.decode(PlistConfiguration.self, from: data)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM