Skip to content

Commit 80b4a16

Browse files
authored
Adds .noEmptyElements option to OutputFormatting (#264)
* Adds `.noEmptyElements` option to OutputFormatting Opts out of empty element shorthand. * Remove unnecessary `if #available` check
1 parent 666227d commit 80b4a16

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

Sources/XMLCoder/Auxiliaries/XMLCoderElement.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -291,12 +291,14 @@ struct XMLCoderElement: Equatable {
291291
formatXMLAttributes(formatting, &string, escapedCharacters.attributes)
292292
}
293293

294-
if !elements.isEmpty {
294+
if !elements.isEmpty || formatting.contains(.noEmptyElements) {
295295
let prettyPrintElements = prettyPrinted && !containsTextNodes
296296
if !key.isEmpty {
297297
string += prettyPrintElements ? ">\n" : ">"
298298
}
299-
formatXMLElements(escapedCharacters, formatting, indentation, &string, level, prettyPrintElements)
299+
if !elements.isEmpty {
300+
formatXMLElements(escapedCharacters, formatting, indentation, &string, level, prettyPrintElements)
301+
}
300302

301303
if prettyPrintElements { string += prefix }
302304
if !key.isEmpty {

Sources/XMLCoder/Encoder/XMLEncoder.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ open class XMLEncoder {
2727

2828
/// Produce XML with keys sorted in lexicographic order.
2929
public static let sortedKeys = OutputFormatting(rawValue: 1 << 1)
30+
31+
/// Produce XML with no short-hand annotation for empty elements, e.g., use `<p></p>` over `</p>`
32+
public static let noEmptyElements = OutputFormatting(rawValue: 1 << 2)
3033
}
3134

3235
/// The indentation to use when XML is pretty-printed.

Tests/XMLCoderTests/NodeEncodingStrategyTests.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,4 +309,23 @@ final class NodeEncodingStrategyTests: XCTestCase {
309309
XCTAssert(false, "failed to decode the example: \(error)")
310310
}
311311
}
312+
313+
314+
func testNoEmptyElements() {
315+
let encoder = XMLEncoder()
316+
encoder.outputFormatting = [.noEmptyElements]
317+
318+
do {
319+
let data = try encoder.encode(UnkeyedContainer(elements: []), withRootKey: "container")
320+
let xml = String(data: data, encoding: .utf8)!
321+
322+
let expected =
323+
"""
324+
<container></container>
325+
"""
326+
XCTAssertEqual(xml, expected)
327+
} catch {
328+
XCTAssert(false, "failed to decode the example: \(error)")
329+
}
330+
}
312331
}

0 commit comments

Comments
 (0)