CoreOffice / XMLCoder

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

Empty (self-closing) tags are decoded as empty string instead of nil #207

Open armadsen opened 3 years ago

armadsen commented 3 years ago

I have some XML that looks like this:

<unit id="foo">
        <name>bar</name>
        <note/>
</unit>

And the corresponding struct:

struct Unit: Codable {
   var id: String
   var name: String
   var note: String?
}

When I decode this, note is set to the empty string (""), rather than nil, which is not what I expect nor want. Is there a way to override this behavior? I can special case it in my own init(from decoder:), but that's a bit of a hassle, so I'm hoping there's some easier way.

(Complete example program here: main.swift.zip)

Thank you so much for the great library! It has made my life a whole lot easier on this little project.

owenzhao commented 3 years ago

I think this is on purpose. As there is note tag in the XML file. For nil, it means there is no note tag at all. If you want otherwise, you can check the value that you get and set it nil when the value is empty.