XML Parser Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓XML Parser runs in O(n) time and O(n) space, in Swift as in every other language.
- ✓XMLParser in Foundation, which is event-driven in the SAX style and reports through a delegate.
- ✓Implement XMLParserDelegate, accumulate text in didFoundCharacters and commit your model object in didEndElement.
- ✓The Swift trap: The tree API being macOS-only is a genuine portability cliff inside one language: XML parsing code written naturally on the Mac with XMLDocument and XPath does not compile for iOS at all, and has to be rewritten against the delegate-based parser, which is a different program rather than a different call.
- ✓Each delegate callback is an Objective-C message send, so per-event overhead is higher than a Swift-native parser would have, and for very large documents that dispatch cost dominates.
What XML Parser actually is
XML Parser in Swift: what you actually reach for
Swift implementation
import Foundation
struct Order {
var id: String = ""
var total: String = ""
}
final class OrderParser: NSObject, XMLParserDelegate {
private(set) var orders: [Order] = []
private var current: Order?
private var text = ""
func parse(_ data: Data) throws -> [Order] {
let parser = XMLParser(data: data)
parser.delegate = self
// Default is already false. Keep it that way.
parser.shouldResolveExternalEntities = false
// parse() returns Bool and reports through the delegate. Ignoring
// the return value means silently accepting a partial document.
guard parser.parse() else {
throw parser.parserError ?? NSError(domain: "xml", code: -1)
}
return orders
}
func parser(_ parser: XMLParser, didStartElement element: String,
namespaceURI: String?, qualifiedName: String?,
attributes: [String: String]) {
text = ""
if element == "order" {
current = Order(id: attributes["id"] ?? "", total: "")
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
text += string // may arrive in SEVERAL chunks: accumulate
}
func parser(_ parser: XMLParser, didEndElement element: String,
namespaceURI: String?, qualifiedName: String?) {
switch element {
case "total": current?.total = text.trimmingCharacters(in: .whitespacesAndNewlines)
case "order": if let o = current { orders.append(o); current = nil }
default: break
}
text = ""
}
}
// XMLDocument + XPath is macOS-ONLY. This does not compile for iOS:
// #if os(macOS)
// let doc = try XMLDocument(data: data)
// let nodes = try doc.nodes(forXPath: "//order/total")
// #endifThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for XML Parser?
XMLParser in Foundation, which is event-driven in the SAX style and reports through a delegate. XMLDocument, the tree API with XPath support, exists on macOS but is not available on iOS.
What is the most common Swift mistake when implementing XML Parser?
The tree API being macOS-only is a genuine portability cliff inside one language: XML parsing code written naturally on the Mac with XMLDocument and XPath does not compile for iOS at all, and has to be rewritten against the delegate-based parser, which is a different program rather than a different call. The second trap is error reporting. XMLParser.parse() returns a Bool and reports problems through an optional delegate callback rather than by throwing, so ignoring the return value means quietly processing whatever was accumulated before the document went wrong. Keep shouldResolveExternalEntities at its default of false.
How does XML Parser actually perform in Swift?
Each delegate callback is an Objective-C message send, so per-event overhead is higher than a Swift-native parser would have, and for very large documents that dispatch cost dominates. Memory stays flat because nothing is materialised, which is the compensating advantage. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.