CoreOffice / XMLCoder

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

Decoding AWS Response and missing attribute or element #255

Closed wmalloc closed 1 year ago

wmalloc commented 1 year ago

I am trying to decode this response

      <?xml version= \"1.0\" encoding= \"UTF-8\"?>
        <ListAllMyBucketsResult xmlns= \"http://s3.amazonaws.com/doc/2006-03-01/\">
            <Buckets>
                <Bucket>
                    <CreationDate>2022-12-25T04:22:03.812Z</CreationDate>
                    <Name>images</Name>
                </Bucket>
                <Bucket>
                    <CreationDate>2022-12-25T04:23:03.352Z</CreationDate>
                    <Name>videos</Name>
                </Bucket>
            </Buckets>
            <Owner>
                <DisplayName>asdfasdfasdfasdfa</DisplayName>
                <ID>asdfasdfasdfasdfa</ID>
            </Owner>
        </ListAllMyBucketsResult>

My structure looks like this.

public struct ListAllMyBucketsResult: Codable {
    public let buckets: [Bucket]
    public let owner: Owner

    public struct Bucket: Codable {
        public let name: String
        public let creationDate: Date

        enum CodingKeys: String, CodingKey {
            case name = "Name"
            case creationDate = "CreationDate"
        }
    }

    public struct Owner: Codable {
        public let id: String
        public let displayName: String

        enum CodingKeys: String, CodingKey {
            case id = "ID"
            case displayName = "DisplayName"
        }
    }

    enum CodingKeys: String, CodingKey {
        case buckets = "Buckets"
        case owner = "Owner"
    }
}

I am getting this error:

debugDescription : "No attribute or element found for key CodingKeys(stringValue: \"Name\", intValue: nil) (\"Name\")."

Thanks for helping,sorry if this is not allowed here.

Joannis commented 1 year ago

Hey! How're you decoding this? Normally I'd expect a different error message if you're decoding ListAllMyBucketsResult. I'm missing the path to the Name key specifically, which should include the parent Buckets

wmalloc commented 1 year ago
        let decoder = XMLDecoder()
        decoder.shouldProcessNamespaces = true
        decoder.dateDecodingStrategy = .formatted(self.dateFormatter)
        return try decoder.decode(ListAllMyBucketsResult.self, from: response.data)
wmalloc commented 1 year ago

I played around some more so I was able to decode but had to add extra object

struct ListAllMyBucketsResult {
let buckets: Buckets
}
struct Buckets {
let bucket: [Bucket]
}

struct Bucket {
let name
let creationDate
}
Joannis commented 1 year ago

Ah right, I also overlooked that. Good thing you spotted it :)