CoreOffice / XMLCoder

Easy XML parsing using Codable protocols in Swift
https://coreoffice.github.io/XMLCoder/
MIT License
795 stars 107 forks source link

Changing the root node name ? #191

Closed gavineadie closed 4 years ago

gavineadie commented 4 years ago

The first example in the README is as follows:

   <note>
     <to>Bob</to>
     <from>Jane</from>
     <heading>Reminder</heading>
     <body>Don't forget to use XMLCoder!</body>
   </note>

which decodes from the above XML into the following structure:

   struct Note: Codable {
     let to: String
     let from: String
     let heading: String
     let body: String
   }

My problem is that the name of my struct (a 'legacy' use) is not the same as the root node name. So I want to decode the above XML into:

   struct Communication: Codable {
     let to: String
     let from: String
     let heading: String
     let body: String
   }

I've explored (am still exploring) the many clevernesses of XMLCoder but not seen this feature. Is there a way to do what I want? Am I overlooking something obvious?

owenzhao commented 4 years ago

For encoding,

let returnData = try? XMLEncoder().encode(note, withRootKey: "communication")

should work.

However, you should do in you own app to upgrade legacy xml to the current. If you don't what to upgrade. You should do something like this

typealias Communication = Note
let note = (try? XMLDecoder().decode(Note.self, from: data)) ?? (try? XMLDecoder().decode(Communication.self, from: data))
MaxDesiatov commented 4 years ago

I don't think there's any need for typealiases, this works out of the box for me. @gavineadie have you tried this previously?

import XMLCoder

let xml = """
   <note>
     <to>Bob</to>
     <from>Jane</from>
     <heading>Reminder</heading>
     <body>Don't forget to use XMLCoder!</body>
   </note>
""".data(using: .utf8)!

struct Communication: Codable {
  let to: String
  let from: String
  let heading: String
  let body: String
}

print(XMLDecoder().decode(Communication.self, from: xml))
gavineadie commented 4 years ago

@MaxDesiatov .. you are correct, issue resolved.