CoreOffice / XMLCoder

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

Empty array fails to parse #283

Open bwees opened 4 months ago

bwees commented 4 months ago

I am on XMLCoder 0.17.1 and Xcode 15.4

I have data that looks like this:

<FixtureType id="test">
  <Wheels>
      <Wheel Name="RotatingGoboWheel">
          <Slot Color="0.312700,0.329000,100.000000" Name="Open"/>
          <Slot Color="0.312700,0.329000,100.000000" MediaFileName="15020276" Name="G01 (Drops Cyclic)"/>
      </Wheel>
  </Wheels>
</FixtureType>

but it can also look like this:

<FixtureType id="test">
  <Wheels />
</FixtureType>

My codable structs look like this:

public struct FixtureType: Codable {
    @Element public var wheels: [Wheel]

    enum CodingKeys: String, CodingKey {
        case wheels = "Wheels"
}

public struct Wheel: Codable {
    @XMLAttribute public var name: String
    public var slots: [WheelSlot]

    enum CodingKeys: String, CodingKey {
        case name = "Name"
        case slots = "Slot"
    }
}

public struct WheelSlot: Codable {
    @Attribute public var name: String
    @Attribute public var color: ColorCIE
    @Attribute public var wheelFilter: String?
    @Attribute public var mediaFilename: String?

    enum CodingKeys: String, CodingKey {
        case name = "Name"
        case color = "Color"
        case wheelFilter = "Filter"
        case mediaFilename = "MediaFileName"
    }
}

The decoding works fine with the first data example (the one with at least one Wheel, but fails to load with the empty <Wheels/> or <Wheels></Wheels> tag with error:

DecodingError
  ▿ typeMismatch : 2 elements
    - .0 : Swift.Array<Any>
    ▿ .1 : Context
      ▿ codingPath : 2 elements
        - 0 : CodingKeys(stringValue: "FixtureType", intValue: nil)
        - 1 : CodingKeys(stringValue: "Wheels", intValue: nil)
      - debugDescription : "Expected to decode Array<Any> but found SingleKeyedBox instead."
      - underlyingError : nil

What changes do I need to make to make the parsing work? I read a few articles that say this library should be able to do this conversion but I cannot seem to make it happen :(.

Thanks for the help!