drmohundro / SWXMLHash

Simple XML parsing in Swift
MIT License
1.41k stars 205 forks source link

Optional value types #187

Closed OgreSwamp closed 6 years ago

OgreSwamp commented 6 years ago

I have an XML where some elements can have no content, e.g.: <midname>Paul</midname> or <midname/>

if I'm parsing it with SWXMLHash to a String? I never get a nil as result. For <midname/> case the parser returns an empty String.

Example:

// parsing element <midname/>
var midname: String? = try element["midname"].value()
// midname value is ""

In deserialize method I wrote extra code to make sure optional has a nil value:

var midnameOpt: String? = try element["midname"].value()
if let midname = midnameOpt, midname.isEmpty {
    midnameOpt = nil
}

But I think that should be done automatically? Would you agree?

drmohundro commented 6 years ago

That is an interesting question... I totally understand what you're saying, too. There is conceptually a difference between <midname></midname> and <midname />. I'd have to research how other XML parsers treat that situation, whether one is an empty string or nil or not because I'd like to behave consistently there.

EDIT - that being said, I think that while those two options look different, they're treated by XML parsers the same.

Regarding why, the underlying reason is that XMLElement's text property is not nillable. See https://github.com/drmohundro/SWXMLHash/blob/master/Source/SWXMLHash.swift#L895-L903.

drmohundro commented 6 years ago

I think I'm going to pass on this feature - the parsers that I researched seem to treat empty elements as empty strings (versus null) aside from a few where you can optionally configure the NULL string to become null. If there are enough other requests, I might reconsider this, though.