有什么简单的方法可以将XML转换为Plist?

时间:2019-09-04 18:42:30

标签: ios swift xml swxmlhash

我在将XML转换为Swift字典然后转换为Plist的过程中正在寻求帮助。

TL; DR 我正在使用SWXMLHash将XML解析为Swift字典,然后解析为Plist,以便用户可以更轻松地编辑数据。解析工作正常,但是我找不到将XMLIndexer对象转换为字典的简单方法,而我的工作方式使我认为应该有一种更简单/可能更复杂的方法。

详细信息:

这是一个示例XML,与我正在研究的非常相似:

 let xmlSample1 = """
<?xml version="1.0" encoding="UTF-8"?>

<root name        = "basic"
        enabled     = "true"
        schema_ver  = "1"
        ver  = “14.0.2”
>

  <initial>
    <actions>

      <list name=“xxxx”> 1234 </list>

      <anotherList name = “xxxx”>
    1234
      </anotherList>


      <config items = "1" max_active = "1">
        <primary=“A B C D” />
      </config>

    </actions>
  </initial>
</root>

这就是我解析它的方式:

 override func viewDidLoad() {
        super.viewDidLoad()
        do {
            let parsedObject: Item = try SWXMLHash.parse(xmSample1)["root"].value()
            convertToDict(parsedObject: parsedObject)
        } catch let error {
            print("error occured:  ---> \(error)")
        }
    }

这是我的解析模型:

struct Item: XMLIndexerDeserializable {
    let name: String
    let enabled: String
    let schema_ver: String
    let ver: String
    let actions: Actions

    static func deserialize(_ node: XMLIndexer) throws -> Item {
        return try Item(
            name: node.value(ofAttribute: "name"),
            enabled: node.value(ofAttribute: "enabled"),
            schema_ver: node.value(ofAttribute: "schema_ver"),
            policy_ver: node.value(ofAttribute: "ver"),
            actions: node["initial"]["actions"].value()
        )
    }
}

这就是我转换为Swift字典的方式:

func convertToDict(parsedObject: Item) {
        let dict = [
            ItemKey.name : parsedObject.name,
            ItemKey.enabled : parsedObject.enabled,
            ItemKey.schema_ver : parsedObject.schema_ver,
            ItemKey.ver : parsedObject.ver,
            ] as [String : Any]

        do {
            try PropertyListEncoder().encode(dict).write(to: fileURL)
            print("saved to plist successfully")
        } catch {
            print(error)
        }
    }

实际的XML比示例的要大,因此转换为字典更加繁琐。有没有更好的方法可以做到这一点,或者我错过了一个现成的解决方案?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使您的Item符合Encodable

  struct Item: XMLIndexerDeserializable, Encodable {
    let name: String
    let enabled: String
    let schema_ver: String
    let ver: String
    let actions: Actions    // this property would have to be Encodable as well
  }

  struct Actions: Encodable {...}

然后,您不必使用字典,与使用字典几乎相同。

func convertToPlist(item: Item) {
      let encoder = PropertyListEncoder()
      encoder.outputFormat = .binary
      do {
          let data = try encoder.encode(item)
          let fileURL = URL(<where you want to save plist>)
          try data.write(to: fileURL)
      } catch {
          // Handle error
          print(error)
      }
}

不确定是否缩小输出。 PropertyListEncoder有几个不同的输出选项。 .binary可能会减小尺寸。

encoder.outputFormat = .binary