Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/XMLCoder/Auxiliaries/KeyedStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ extension KeyedStorage where Key == String, Value == Box {
} else if let value = element.value {
result.append(StringBox(value), at: element.key)
} else {
result.append(NullBox(), at: element.key)
result.append(SingleKeyedBox(key: element.key, element: NullBox()), at: element.key)
}

return result
Expand Down
20 changes: 18 additions & 2 deletions Sources/XMLCoder/Decoder/XMLKeyedDecodingContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ struct XMLKeyedDecodingContainer<K: CodingKey>: KeyedDecodingContainerProtocol {

let box = elements.first ?? attributes.first

if let singleKeyed = box as? SingleKeyedBox {
return singleKeyed.element.isNull
}

return box?.isNull ?? true
}

Expand Down Expand Up @@ -232,14 +236,26 @@ extension XMLKeyedDecodingContainer {
let keyString = key.stringValue.isEmpty ? "value" : key.stringValue
let value = keyedBox.elements[keyString]
if !value.isEmpty {
return value
return value.map {
if let singleKeyed = $0 as? SingleKeyedBox {
return singleKeyed.element
} else {
return $0
}
}
} else if let value = keyedBox.value {
return [value]
} else {
return []
}
} else {
return keyedBox.elements[key.stringValue]
return keyedBox.elements[key.stringValue].map {
if let singleKeyed = $0 as? SingleKeyedBox {
return singleKeyed.element
} else {
return $0
}
}
}
}

Expand Down
44 changes: 44 additions & 0 deletions Tests/XMLCoderTests/NestedChoiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,50 @@ class NestedChoiceTests: XCTestCase {
XCTAssertEqual(result, expected)
}

func testNestedEnumsWithEmptyStruct() throws {
let xml = """
<container>
<p>
<br></br>
<run>
<id>1518</id>
<text>I am answering it again.</text>
</run>
<properties>
<id>431</id>
<title>A Word About Wake Times</title>
</properties>
</p>
<p>
<run>
<id>1519</id>
<text>I am answering it again.</text>
</run>
<br />
</p>
</container>
"""
let result = try XMLDecoder().decode(Container.self, from: xml.data(using: .utf8)!)
let expected = Container(
paragraphs: [
Paragraph(
entries: [
.br(Break()),
.run(Run(id: 1518, text: "I am answering it again.")),
.properties(Properties(id: 431, title: "A Word About Wake Times")),
]
),
Paragraph(
entries: [
.run(Run(id: 1519, text: "I am answering it again.")),
.br(Break()),
]
),
]
)
XCTAssertEqual(result, expected)
}

func testNestedEnumsRoundTrip() throws {
let original = Container(
paragraphs: [
Expand Down