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

Adding all elements with same prefix to their own struct. #288

Open
jubishop opened this issue Jan 1, 2025 · 1 comment
Open

Adding all elements with same prefix to their own struct. #288

jubishop opened this issue Jan 1, 2025 · 1 comment

Comments

@jubishop
Copy link

jubishop commented Jan 1, 2025

say I have this xml:

  <channel>
    <title>The Changelog: Software Development, Open Source</title>
    <itunes:summary>Software&apos;s best weekly news brief, deep technical interviews &amp; talk show.</itunes:summary>
    <itunes:author>Changelog Media</itunes:author>
 </channel>

which is a stripped down example from the real world of parsing Podcast RSS Feeds :)

It'd be great if I could decode that into something like:

struct Channel: Codable {
 let title:String
 
 struct iTunes: Codable {
   let summary: String
   let author: String
 }
}

I know I can store all three values in a single flat Channel structure given what's in the Readme, but is there any advanced way to cause this deeper structuring, putting the elements prefixed with iTunes: into the nested iTunes struct?

Right now my flattened version looks like this:

  struct Channel: Codable {
    let title: String
    let itunesSummary: String?
    let itunesAuthor: String?

    enum CodingKeys: String, CodingKey {
      case title
      case itunesSummary = "itunes:summary"
      case itunesAuthor = "itunes:author"
    }
  }
@jubishop
Copy link
Author

jubishop commented Jan 1, 2025

I can, of course, implement my own init(from: decoder) method, which looks something like this for me right now:

  struct Channel: Decodable {
    let title: String
    let iTunes: iTunesNamespace

    enum CodingKeys: String, CodingKey {
      case title
    }

    struct iTunesNamespace: Decodable {
      let summary: String?
      let author: String?

      enum CodingKeys: String, CodingKey {
        case summary = "itunes:summary"
        case author = "itunes:author"
      }
    }
    
    init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: CodingKeys.self)
      title = try container.decode(String.self, forKey: .title)
      iTunes = try iTunesNamespace.init(from: decoder)
    }
  }

this just gets to be a little verbose. any ideas on how to shorten would be appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant