3 /// Simple wrapper around `Foundation.XMLParser`.
4 internal class AEXMLParser: NSObject, XMLParserDelegate {
8 let document: AEXMLDocument
11 var currentParent: AEXMLElement?
12 var currentElement: AEXMLElement?
13 var currentValue = String()
15 var parseError: Error?
17 private lazy var trimWhitespace: Bool = {
18 let trim = self.document.options.parserSettings.shouldTrimWhitespace
24 init(document: AEXMLDocument, data: Data) {
25 self.document = document
27 currentParent = document
35 let parser = XMLParser(data: data)
36 parser.delegate = self
38 parser.shouldProcessNamespaces = document.options.parserSettings.shouldProcessNamespaces
39 parser.shouldReportNamespacePrefixes = document.options.parserSettings.shouldReportNamespacePrefixes
40 parser.shouldResolveExternalEntities = document.options.parserSettings.shouldResolveExternalEntities
42 let success = parser.parse()
45 guard let error = parseError else { throw AEXMLError.parsingFailed }
50 // MARK: - XMLParserDelegate
52 func parser(_ parser: XMLParser,
53 didStartElement elementName: String,
54 namespaceURI: String?,
55 qualifiedName qName: String?,
56 attributes attributeDict: [String : String])
58 currentValue = String()
59 currentElement = currentParent?.addChild(name: elementName, attributes: attributeDict)
60 currentParent = currentElement
63 func parser(_ parser: XMLParser, foundCharacters string: String) {
64 currentValue.append(trimWhitespace ? string.trimmingCharacters(in: .whitespacesAndNewlines) : string)
65 currentElement?.value = currentValue.isEmpty ? nil : currentValue
68 func parser(_ parser: XMLParser,
69 didEndElement elementName: String,
70 namespaceURI: String?,
71 qualifiedName qName: String?)
73 currentParent = currentParent?.parent
77 func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
78 self.parseError = parseError