Skip to content

Commit a4475f1

Browse files
authored
Merge pull request #1 from tachyonics/master
Handle empty XML elements and unit test.
2 parents 344c27d + 6270a69 commit a4475f1

File tree

2 files changed

+70
-6
lines changed

2 files changed

+70
-6
lines changed

Sources/XMLCoding/XMLStackParser.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,10 @@ internal class _XMLElement {
183183
} else {
184184
node[childElement.key] = newValue
185185
}
186+
// if the node is empty and there is no existing value
187+
} else if node[childElement.key] == nil {
188+
// an empty node can be treated as an empty dictionary
189+
node[childElement.key] = [:]
186190
}
187191
}
188192
}

Tests/XMLCodingTests/XMLParsingTests.swift

Lines changed: 66 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,75 @@ import XCTest
33

44

55
class XMLParsingTests: XCTestCase {
6-
func testExample() {
7-
// This is an example of a functional test case.
8-
// Use XCTAssert and related functions to verify your tests produce the correct
9-
// results.
10-
// XCTAssertEqual(XMLParsing().text, "Hello, World!")
6+
struct Result: Codable {
7+
let message: String?
8+
9+
enum CodingKeys: String, CodingKey {
10+
case message = "Message"
11+
}
12+
}
13+
14+
struct Metadata: Codable {
15+
let id: String
16+
17+
enum CodingKeys: String, CodingKey {
18+
case id = "Id"
19+
}
20+
}
21+
22+
struct Response: Codable {
23+
let result: Result
24+
let metadata: Metadata
25+
26+
enum CodingKeys: String, CodingKey {
27+
case result = "Result"
28+
case metadata = "Metadata"
29+
}
30+
}
31+
32+
func testEmptyElement() throws {
33+
let inputString = """
34+
<Response>
35+
<Result/>
36+
<Metadata>
37+
<Id>id</Id>
38+
</Metadata>
39+
</Response>
40+
"""
41+
42+
guard let inputData = inputString.data(using: .utf8) else {
43+
return XCTFail()
44+
}
45+
46+
let response = try XMLDecoder().decode(Response.self, from: inputData)
47+
48+
XCTAssertNil(response.result.message)
1149
}
1250

51+
func testEmptyElementNotEffectingPreviousElement() throws {
52+
let inputString = """
53+
<Response>
54+
<Result>
55+
<Message>message</Message>
56+
</Result>
57+
<Result/>
58+
<Metadata>
59+
<Id>id</Id>
60+
</Metadata>
61+
</Response>
62+
"""
63+
64+
guard let inputData = inputString.data(using: .utf8) else {
65+
return XCTFail()
66+
}
67+
68+
let response = try XMLDecoder().decode(Response.self, from: inputData)
69+
70+
XCTAssertEqual("message", response.result.message)
71+
}
1372

1473
static var allTests = [
15-
("testExample", testExample),
74+
("testEmptyElement", testEmptyElement),
75+
("testEmptyElementNotEffectingPreviousElement", testEmptyElementNotEffectingPreviousElement),
1676
]
1777
}

0 commit comments

Comments
 (0)