CoreOffice / XMLCoder

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

This framework really works? keyNotFound #249

Open Rufy86 opened 2 years ago

Rufy86 commented 2 years ago

I'm try to decode an XML returned by an API. the result is an error:

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "ns2:body", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "ns2:body", intValue: nil)], debugDescription: "No attribute or element found for key CodingKeys(stringValue: \"ns2:body\", intValue: nil) (\"ns2:body\").", underlyingError: nil))

this is the struct `struct AirportList:Codable { let ns2:String

enum CodingKeys: String, CodingKey {
    case ns2 = "ns2:body"
}

}` I've changed the key in model class, with any tag I need but the result is the same.

this framework really works?

Joannis commented 2 years ago

This should work, and is in our unit tests. Have you set decoder.shouldProcessNamespaces = true? That causes the namespaces to be stripped.

mflint commented 2 years ago

Hello @Rufy86,

In your code, ns2 is the namespace, which is different from the property name. If you don't care about namespaces, then the easiest solution might be:

struct AirportList: Codable {
  let body: String
}

// and to decode the XML...
let decoder = XMLDecoder()
decoder.shouldProcessNamespaces = true
let airportList = try decoder.decode(AirportList.self, from: data)
Rufy86 commented 2 years ago

thank you very much for the answer but I've still problems this is a piece oaf my xml `<?xml version="1.0" encoding="utf-8" ?>

F12887A97073B98718174A8AFCDE5F65 true AAL_APT_0001AAL Int AAL Aalborg DK Danimarca Europa 57,09275891 9,849243164 AES_APT_0019AES Aalesund Vigra AES Aalesund NO Norvegia Europa 62,5625 6,119699955 AAR_APT_0001AAR Aarhus Airport AAR Aarhus DK Danimarca Europa 56,2999992 10,6190004 ` Now I've no error from decoder but the objects are empty this is my code: `AF.request("url_to_my_api").responseData { response in guard let airportList = response.data else { return } let decoder = XMLDecoder() decoder.shouldProcessNamespaces = true let note = try! decoder.decode(AirportList.self, from: airportList) print(note) }`
Joannis commented 2 years ago

@Rufy86 are you expecting the whole hierarchy of XML inside that String? Because if so, that's not how XMLCoder was designed. Each XML element or attribute is decoded into it's own codable key/value. So you'll need to model your Codable type to match the expectations in XML.