-
Notifications
You must be signed in to change notification settings - Fork 104
/
XMLElement.swift
231 lines (193 loc) · 9.67 KB
/
XMLElement.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
//
// XMLElement.swift
// XMLCoder
//
// Created by Vincent Esche on 12/18/18.
//
import Foundation
class _XMLElement {
static let attributesKey = "___ATTRIBUTES"
static let escapedCharacterSet = [("&", "&"), ("<", "<"), (">", ">"), ("'", "'"), ("\"", """)]
var key: String
var value: String?
var attributes: [String: String] = [:]
var children: [String: [_XMLElement]] = [:]
init(key: String, value: String? = nil, attributes: [String: String] = [:], children: [String: [_XMLElement]] = [:]) {
self.key = key
self.value = value
self.attributes = attributes
self.children = children
}
static func createRootElement(rootKey: String, object: UnkeyedBox) -> _XMLElement? {
let element = _XMLElement(key: rootKey)
_XMLElement.createElement(parentElement: element, key: rootKey, object: object)
return element
}
static func createRootElement(rootKey: String, object: KeyedBox) -> _XMLElement? {
let element = _XMLElement(key: rootKey)
_XMLElement.modifyElement(element: element, parentElement: nil, key: nil, object: object)
return element
}
fileprivate static func modifyElement(element: _XMLElement, parentElement: _XMLElement?, key: String?, object: KeyedBox) {
let attributesBox = object[_XMLElement.attributesKey] as? KeyedBox
let uniqueAttributes: [(String, String)]? = attributesBox?.unbox().compactMap { key, box in
return box.xmlString().map { (key, $0) }
}
element.attributes = uniqueAttributes.map { Dictionary(uniqueKeysWithValues: $0) } ?? [:]
let objects = object.filter { key, _value in key != _XMLElement.attributesKey }
for (key, box) in objects {
_XMLElement.createElement(parentElement: element, key: key, object: box)
}
if let parentElement = parentElement, let key = key {
parentElement.children[key] = (parentElement.children[key] ?? []) + [element]
}
}
fileprivate static func createElement(parentElement: _XMLElement, key: String, object: Box) {
switch object {
case let box as UnkeyedBox:
for box in box.unbox() {
_XMLElement.createElement(parentElement: parentElement, key: key, object: box)
}
case let box as KeyedBox:
modifyElement(element: _XMLElement(key: key), parentElement: parentElement, key: key, object: box)
case _:
let element = _XMLElement(key: key, value: object.xmlString())
parentElement.children[key, default: []].append(element)
}
}
func append(value string: String) {
var value = self.value ?? ""
value += string.trimmingCharacters(in: .whitespacesAndNewlines)
self.value = value
}
func flatten() -> [String: Box] {
var node: [String: Box] = attributes.mapValues { StringBox($0) }
for childElement in children {
for child in childElement.value {
if let content = child.value {
if let oldContent = node[childElement.key] as? UnkeyedBox {
oldContent.append(StringBox(content))
// FIXME: Box is a reference type, so this shouldn't be necessary:
node[childElement.key] = oldContent
} else if let oldContent = node[childElement.key] {
node[childElement.key] = UnkeyedBox([oldContent, StringBox(content)])
} else {
node[childElement.key] = StringBox(content)
}
} else if !child.children.isEmpty || !child.attributes.isEmpty {
let newValue = child.flatten()
if let existingValue = node[childElement.key] {
if let unkeyed = existingValue as? UnkeyedBox {
unkeyed.append(KeyedBox(newValue))
// FIXME: Box is a reference type, so this shouldn't be necessary:
node[childElement.key] = unkeyed
} else {
node[childElement.key] = UnkeyedBox([existingValue, KeyedBox(newValue)])
}
} else {
node[childElement.key] = KeyedBox(newValue)
}
}
}
}
return node
}
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)
}
fileprivate func formatUnsortedXMLElements(_ string: inout String, _ level: Int, _ cdata: Bool, _ formatting: XMLEncoder.OutputFormatting, _ prettyPrinted: Bool) {
formatXMLElements(from: children.map { (key: $0, value: $1) }, into: &string, at: level, cdata: cdata, formatting: formatting, prettyPrinted: prettyPrinted)
}
fileprivate func elementString(for childElement: (key: String, value: [_XMLElement]), at level: Int, cdata: Bool, formatting: XMLEncoder.OutputFormatting, prettyPrinted: Bool) -> String {
var string = ""
for child in childElement.value {
string += child._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: children.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(_XMLElement.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 children: [(key: String, value: [_XMLElement])], into string: inout String, at level: Int, cdata: Bool, formatting: XMLEncoder.OutputFormatting, prettyPrinted: Bool) {
for childElement in children {
string += elementString(for: childElement, 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)
}
fileprivate func formatXMLAttributes(_ formatting: XMLEncoder.OutputFormatting, _ string: inout String) {
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
if formatting.contains(.sortedKeys) {
formatSortedXMLAttributes(&string)
return
}
formatUnsortedXMLAttributes(&string)
return
}
formatUnsortedXMLAttributes(&string)
}
fileprivate func formatXMLElements(_ formatting: XMLEncoder.OutputFormatting, _ string: inout String, _ level: Int, _ cdata: Bool, _ prettyPrinted: Bool) {
if #available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
if formatting.contains(.sortedKeys) {
formatSortedXMLElements(&string, level, cdata, formatting, prettyPrinted)
return
}
formatUnsortedXMLElements(&string, level, cdata, formatting, prettyPrinted)
return
}
formatUnsortedXMLElements(&string, level, cdata, formatting, prettyPrinted)
}
fileprivate 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
string += "<\(key)"
formatXMLAttributes(formatting, &string)
if let value = value {
string += ">"
if !ignoreEscaping {
string += (cdata == true ? "<![CDATA[\(value)]]>" : "\(value.escape(_XMLElement.escapedCharacterSet))")
} else {
string += "\(value)"
}
string += "</\(key)>"
} else if !children.isEmpty {
string += prettyPrinted ? ">\n" : ">"
formatXMLElements(formatting, &string, level, cdata, prettyPrinted)
string += indentation
string += "</\(key)>"
} else {
string += " />"
}
return string
}
}
extension _XMLElement: Equatable {
static func == (lhs: _XMLElement, rhs: _XMLElement) -> Bool {
guard
lhs.key == rhs.key,
lhs.value == rhs.value,
lhs.attributes == rhs.attributes,
lhs.children == rhs.children
else {
return false
}
return true
}
}