ShawnMoore / XMLParsing

XMLEncoder & XMLDecoder using the codable protocol in Swift 4.2
MIT License
332 stars 100 forks source link

Issue parsing XML file in key value structure #44

Open zoufishanmehdi opened 5 years ago

zoufishanmehdi commented 5 years ago

Hi, I'm trying to parse an XML file that has a key value structure but it doesn't look like it's supported. You can see the XML file using the link and the model can be seen below. How can I parse the file below using this library?

Link to XML file: http://mobile.public.ec2.nytimes.com.s3-website-us-east-1.amazonaws.com/candidates/content/v1/articles.plist


struct Articles: Codable {
    let article: [Dict]

    enum CodingKeys: String, CodingKey {
        case article = "dict"
    }

}

struct Dict: Codable {
    let title: String
    let body: String
    let images: [Images]
}

struct Images: Codable {
    let height: Int
    let url: String

}
MaxDesiatov commented 5 years ago

HI @zoufishanmehdi, you probably don't need XMLDecoder for this kind of format as a more high-level PropertyListDecoder would work. You also wouldn't need the Articles type in your snippet, Dict and Images are enough to decode it like this:

import Foundation

let result = try PropertyListDecoder().decode([Dict].self, from: simpleXML)

I hope this works for you!