Skip to content

Commit

Permalink
Adds .noEmptyElements option to OutputFormatting (#264)
Browse files Browse the repository at this point in the history
* Adds `.noEmptyElements` option to OutputFormatting

Opts out of empty element shorthand.

* Remove unnecessary `if #available` check
  • Loading branch information
nighthawk authored May 2, 2023
1 parent 666227d commit 80b4a16
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
6 changes: 4 additions & 2 deletions Sources/XMLCoder/Auxiliaries/XMLCoderElement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -291,12 +291,14 @@ struct XMLCoderElement: Equatable {
formatXMLAttributes(formatting, &string, escapedCharacters.attributes)
}

if !elements.isEmpty {
if !elements.isEmpty || formatting.contains(.noEmptyElements) {
let prettyPrintElements = prettyPrinted && !containsTextNodes
if !key.isEmpty {
string += prettyPrintElements ? ">\n" : ">"
}
formatXMLElements(escapedCharacters, formatting, indentation, &string, level, prettyPrintElements)
if !elements.isEmpty {
formatXMLElements(escapedCharacters, formatting, indentation, &string, level, prettyPrintElements)
}

if prettyPrintElements { string += prefix }
if !key.isEmpty {
Expand Down
3 changes: 3 additions & 0 deletions Sources/XMLCoder/Encoder/XMLEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ open class XMLEncoder {

/// Produce XML with keys sorted in lexicographic order.
public static let sortedKeys = OutputFormatting(rawValue: 1 << 1)

/// Produce XML with no short-hand annotation for empty elements, e.g., use `<p></p>` over `</p>`
public static let noEmptyElements = OutputFormatting(rawValue: 1 << 2)
}

/// The indentation to use when XML is pretty-printed.
Expand Down
19 changes: 19 additions & 0 deletions Tests/XMLCoderTests/NodeEncodingStrategyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -309,4 +309,23 @@ final class NodeEncodingStrategyTests: XCTestCase {
XCTAssert(false, "failed to decode the example: \(error)")
}
}


func testNoEmptyElements() {
let encoder = XMLEncoder()
encoder.outputFormatting = [.noEmptyElements]

do {
let data = try encoder.encode(UnkeyedContainer(elements: []), withRootKey: "container")
let xml = String(data: data, encoding: .utf8)!

let expected =
"""
<container></container>
"""
XCTAssertEqual(xml, expected)
} catch {
XCTAssert(false, "failed to decode the example: \(error)")
}
}
}

0 comments on commit 80b4a16

Please sign in to comment.