XMLCoder icon indicating copy to clipboard operation
XMLCoder copied to clipboard

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

Open armadsen opened this issue 4 years ago • 1 comments

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.

armadsen avatar Dec 30 '20 21:12 armadsen

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.

owenzhao avatar Dec 31 '20 09:12 owenzhao