forked from CoreOffice/XMLCoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLCoderElement.swift
356 lines (317 loc) · 11.2 KB
/
XMLCoderElement.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//
// XMLCoderElement.swift
// XMLCoder
//
// Created by Vincent Esche on 12/18/18.
//
import Foundation
struct XMLCoderElement: Equatable {
static let attributesKey = "___ATTRIBUTES"
static let escapedCharacterSet = [
("&", "&"),
("<", "<"),
(">", ">"),
("'", "'"),
("\"", """),
]
var key: String
var value: String?
var elements: [XMLCoderElement] = []
var attributes: [String: String] = [:]
init(
key: String,
value: String? = nil,
elements: [XMLCoderElement] = [],
attributes: [String: String] = [:]
) {
self.key = key
self.value = value
self.elements = elements
self.attributes = attributes
}
mutating func append(value string: String) {
var value = self.value ?? ""
value += string.trimmingCharacters(in: .whitespacesAndNewlines)
self.value = value
}
mutating func append(element: XMLCoderElement, forKey key: String) {
elements.append(element)
}
func flatten() -> KeyedBox {
let attributes = self.attributes.mapValues { StringBox($0) }
var keyedElements: [String: Box] = elements.reduce([String: Box]()) { (result, element) -> [String: Box] in
var result = result
let key = element.key
let hasValue = element.value != nil
let hasElements = !element.elements.isEmpty
let hasAttributes = !element.attributes.isEmpty
if hasValue || hasElements || hasAttributes {
if let content = element.value {
switch result[key] {
case var unkeyedBox as UnkeyedBox:
unkeyedBox.append(StringBox(content))
result[key] = unkeyedBox
case let stringBox as StringBox:
result[key] = UnkeyedBox([stringBox, StringBox(content)])
default:
result[key] = StringBox(content)
}
}
if hasElements || hasAttributes {
let content = element.flatten()
switch result[key] {
case var unkeyedBox as UnkeyedBox:
unkeyedBox.append(content)
result[key] = unkeyedBox
case let box?:
result[key] = UnkeyedBox([box, content])
default:
result[key] = content
}
}
} else {
switch result[key] {
case var unkeyedBox as UnkeyedBox:
unkeyedBox.append(NullBox())
result[key] = unkeyedBox
case let box?:
result[key] = UnkeyedBox([box, NullBox()])
default:
result[key] = NullBox()
}
}
return result
}
// Handle attributed unkeyed valye <foo attr="bar">zap</foo>
// Value should be zap. Detect only when no other elements exist
if keyedElements.isEmpty, let value = value {
keyedElements["value"] = StringBox(value)
}
let keyedBox = KeyedBox(elements: keyedElements, attributes: attributes)
return keyedBox
}
func toXMLString(with header: XMLHeader? = nil,
withCDATA cdata: Bool,
formatting: XMLEncoder.OutputFormatting,
ignoreEscaping _: Bool = false) -> String {
if let header = header, let headerXML = header.toXML() {
return headerXML + _toXMLString(withCDATA: cdata, formatting: formatting)
}
return _toXMLString(withCDATA: cdata, formatting: formatting)
}
private func formatUnsortedXMLElements(
_ string: inout String,
_ level: Int,
_ cdata: Bool,
_ formatting: XMLEncoder.OutputFormatting,
_ prettyPrinted: Bool
) {
formatXMLElements(
from: elements,
into: &string,
at: level,
cdata: cdata,
formatting: formatting,
prettyPrinted: prettyPrinted
)
}
fileprivate func elementString(
for element: XMLCoderElement,
at level: Int,
cdata: Bool,
formatting: XMLEncoder.OutputFormatting,
prettyPrinted: Bool
) -> String {
var string = ""
string += element._toXMLString(
indented: level + 1, withCDATA: cdata, formatting: formatting
)
string += prettyPrinted ? "\n" : ""
return string
}
fileprivate func formatSortedXMLElements(
_ string: inout String,
_ level: Int,
_ cdata: Bool,
_ formatting: XMLEncoder.OutputFormatting,
_ prettyPrinted: Bool
) {
formatXMLElements(from: elements.sorted { $0.key < $1.key },
into: &string,
at: level,
cdata: cdata,
formatting: formatting,
prettyPrinted: prettyPrinted)
}
fileprivate func attributeString(key: String, value: String) -> String {
return " \(key)=\"\(value.escape(XMLCoderElement.escapedCharacterSet))\""
}
fileprivate func formatXMLAttributes(
from keyValuePairs: [(key: String, value: String)],
into string: inout String
) {
for (key, value) in keyValuePairs {
string += attributeString(key: key, value: value)
}
}
fileprivate func formatXMLElements(
from elements: [XMLCoderElement],
into string: inout String,
at level: Int,
cdata: Bool,
formatting: XMLEncoder.OutputFormatting,
prettyPrinted: Bool
) {
for element in elements {
string += elementString(for: element,
at: level,
cdata: cdata,
formatting: formatting,
prettyPrinted: prettyPrinted)
}
}
fileprivate func formatSortedXMLAttributes(_ string: inout String) {
formatXMLAttributes(
from: attributes.sorted(by: { $0.key < $1.key }), into: &string
)
}
fileprivate func formatUnsortedXMLAttributes(_ string: inout String) {
formatXMLAttributes(
from: attributes.map { (key: $0, value: $1) }, into: &string
)
}
private func formatXMLAttributes(
_ formatting: XMLEncoder.OutputFormatting,
_ string: inout String
) {
if formatting.contains(.sortedKeys) {
formatSortedXMLAttributes(&string)
return
}
formatUnsortedXMLAttributes(&string)
}
private func formatXMLElements(
_ formatting: XMLEncoder.OutputFormatting,
_ string: inout String,
_ level: Int,
_ cdata: Bool,
_ prettyPrinted: Bool
) {
if formatting.contains(.sortedKeys) {
formatSortedXMLElements(
&string, level, cdata, formatting, prettyPrinted
)
return
}
formatUnsortedXMLElements(
&string, level, cdata, formatting, prettyPrinted
)
}
private func _toXMLString(
indented level: Int = 0,
withCDATA cdata: Bool,
formatting: XMLEncoder.OutputFormatting,
ignoreEscaping: Bool = false
) -> String {
let prettyPrinted = formatting.contains(.prettyPrinted)
let indentation = String(
repeating: " ", count: (prettyPrinted ? level : 0) * 4
)
var string = indentation
if !key.isEmpty {
string += "<\(key)"
}
formatXMLAttributes(formatting, &string)
if let value = value {
if !key.isEmpty {
string += ">"
}
if !ignoreEscaping {
string += (cdata == true ? "<![CDATA[\(value)]]>" :
"\(value.escape(XMLCoderElement.escapedCharacterSet))")
} else {
string += "\(value)"
}
if !key.isEmpty {
string += "</\(key)>"
}
} else if !elements.isEmpty {
string += prettyPrinted ? ">\n" : ">"
formatXMLElements(formatting, &string, level, cdata, prettyPrinted)
string += indentation
if !key.isEmpty {
string += "</\(key)>"
}
} else {
string += " />"
}
return string
}
}
// MARK: - Convenience Initializers
extension XMLCoderElement {
init(key: String, box: UnkeyedBox) {
let elements = box.map { box in
XMLCoderElement(key: key, box: box)
}
self.init(key: key, elements: elements)
}
init(key: String, box: KeyedBox) {
var elements: [XMLCoderElement] = []
for (key, box) in box.elements {
let fail = {
preconditionFailure("Unclassified box: \(type(of: box))")
}
switch box {
case let sharedUnkeyedBox as SharedBox<UnkeyedBox>:
let box = sharedUnkeyedBox.unbox()
elements.append(contentsOf: box.map {
XMLCoderElement(key: key, box: $0)
})
case let unkeyedBox as UnkeyedBox:
// This basically injects the unkeyed children directly into self:
elements.append(contentsOf: unkeyedBox.map {
XMLCoderElement(key: key, box: $0)
})
case let sharedKeyedBox as SharedBox<KeyedBox>:
let box = sharedKeyedBox.unbox()
elements.append(XMLCoderElement(key: key, box: box))
case let keyedBox as KeyedBox:
elements.append(XMLCoderElement(key: key, box: keyedBox))
case let simpleBox as SimpleBox:
elements.append(XMLCoderElement(key: key, box: simpleBox))
default:
fail()
}
}
let attributes: [String: String] = Dictionary(
uniqueKeysWithValues: box.attributes.compactMap { key, box in
guard let value = box.xmlString() else {
return nil
}
return (key, value)
}
)
self.init(key: key, elements: elements, attributes: attributes)
}
init(key: String, box: SimpleBox) {
self.init(key: key)
value = box.xmlString()
}
init(key: String, box: Box) {
switch box {
case let sharedUnkeyedBox as SharedBox<UnkeyedBox>:
self.init(key: key, box: sharedUnkeyedBox.unbox())
case let sharedKeyedBox as SharedBox<KeyedBox>:
self.init(key: key, box: sharedKeyedBox.unbox())
case let unkeyedBox as UnkeyedBox:
self.init(key: key, box: unkeyedBox)
case let keyedBox as KeyedBox:
self.init(key: key, box: keyedBox)
case let simpleBox as SimpleBox:
self.init(key: key, box: simpleBox)
case let box:
preconditionFailure("Unclassified box: \(type(of: box))")
}
}
}