Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changing the root node name ? #191

Closed
gavineadie opened this issue Jun 8, 2020 · 3 comments
Closed

Changing the root node name ? #191

gavineadie opened this issue Jun 8, 2020 · 3 comments
Assignees
Labels
more info needed Not enough details available to proceed

Comments

@gavineadie
Copy link

gavineadie commented Jun 8, 2020

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
Copy link
Collaborator

owenzhao commented Jun 8, 2020

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
Copy link
Collaborator

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))

@MaxDesiatov MaxDesiatov added the more info needed Not enough details available to proceed label Jun 8, 2020
@gavineadie
Copy link
Author

@MaxDesiatov .. you are correct, issue resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
more info needed Not enough details available to proceed
Projects
None yet
Development

No branches or pull requests

3 participants