CoreOffice / XMLCoder

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

How to encode empty tags as enum based on name #202

Closed alexanderwe closed 1 year ago

alexanderwe commented 3 years ago

Hey, at first thanks a lot for making this library, great work!

I am rather new to the XML game and trying to decode WebDAV responses. So I have the following response from the server:

<?xml version="1.0" standalone="yes"?>
<d:multistatus xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns">
    <d:response>
        <d:href>someURL</d:href>
        <d:propstat>
            <d:prop>
                <d:resourcetype>
                    <d:collection></d:collection>
                </d:resourcetype>
            </d:prop>
            <d:status>HTTP/1.1 200 OK</d:status>
        </d:propstat>
    </d:response>
</d:multistatus>

And the following Codable models:

struct MultiStatus: Codable {
    let responses: [MultiStatusResponse]

    enum CodingKeys: String, CodingKey {
        case responses = "response"
    }
}

struct MultiStatusResponse: Codable {
    struct Property: Codable {
        enum ResourceType: Codable {
            case collection
            case file
            case redirect
        }

        let ressourceType: ResourceType
    }

    let href: String
    let properties: [Property]
    let error: String?

    enum CodingKeys: String, CodingKey {
        case href
        case properties = "prop"
        case error
    }
}

-> This implementation does not work, because it is complaining about the ResourceType enum not conforming to Codable because of the missing method implementations of decode and encode.

I am searching for a way to decode the

  <d:resourcetype>
      <d:collection></d:collection>
  </d:resourcetype>

part into an enum case based on the tag inside the <d:resourcetype> tag. So in this case I would like the ResourceType enum to be of case collection. Is that possible with your library or do I need to go one level deeper and parse the XML by myself ? I tried to write custom decode and encode methods but unfortunately didn't get it to work.

CWeykopf commented 2 years ago

Is there a solution. I run into a similar problem.