CoreOffice / XMLCoder

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

Option for XMLEncoder not to self-close tags? #135

Closed DJBen closed 5 years ago

DJBen commented 5 years ago

Hi I try to find ways to make XMLEncoder NOT to produce self-closing tags.

i.e. I would like <tag id="1"></tag> rather than <tag id="1" />. Do we have a way to customize this?

Thank you

MaxDesiatov commented 5 years ago

Hi @DJBen, within XMLCoder we treat both forms differently, since a self-closing tag indicates an absence of a value, while an opening and a closing tag denote an empty value (e.g. an empty string), see this StackOverflow answer for more details. In my opinion the simplest solution would be to leverage the value intrinsic:

struct Tag: Codable, DynamicNodeEncoding {
  let id: Int
  let value = ""

  enum CodingKeys: String, CodingKey {
    case id
    case value = ""
  }

  static func nodeEncoding(for key: CodingKey) -> XMLEncoder.NodeEncoding {
    switch key {
      case CodingKeys.id:
        return .attribute
      default:
        return .element
      }
  }
}

I hope this resolves your question?

DJBen commented 5 years ago

That sounds good. Thanks.