Working with XML in Swift: Parsing, Creating, and Processing Data (iOS/macOS)

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with XML in Swift (iOS/macOS): From Parsing to Creation



XML (eXtensible Markup Language) continues to be used in legacy systems, web services (SOAP, RSS), and configuration files. In Swift for iOS/macOS, there is no built-in library with syntactic sugar, but there is a powerful XMLParser (SAX parser), as well as the popular third-party library AEXML (DOM approach). In this article, we will cover both approaches.



1. Built-in XMLParser (SAX Approach)



XMLParser is an event-driven (SAX) parser from Foundation. It does not load the entire document into memory but calls delegate methods when encountering elements. Ideal for large files.



Example: Parsing an RSS Feed



import Foundation

class RSSParser: NSObject, XMLParserDelegate { private var currentElement = "" private var currentTitle = "" private var items: [String] = []

func parse(data: Data) -> [String] { let parser = XMLParser(data: data) parser.delegate = self parser.parse() return items }

// MARK: - XMLParserDelegate func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { currentElement = elementName if elementName == "item" { currentTitle = "" } }

func parser(_ parser: XMLParser, foundCharacters string: String) { if currentElement == "title" { currentTitle += string } }

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "title" && !currentTitle.isEmpty { items.append(currentTitle.trimmingCharacters(in: .whitespacesAndNewlines)) } }}

// Usagelet xmlString = """<rss> <channel> <item><title>Swift 6.0</title></item> <item><title>New Xcode Features</title></item> </channel></rss>"""if let data = xmlString.data(using: .utf8) { let parser = RSSParser() let titles = parser.parse(data: data) print(titles) // ["Swift 6.0", "New Xcode Features"]}


Important: foundCharacters may be called multiple times for a single text node (especially with Cyrillic characters). Always accumulate the string, do not assign it.



2. AEXML — Convenient DOM Library



AEXML is a lightweight library for working with XML in a DOM style. It allows reading and creating XML without manual event management. It can be installed via Swift Package Manager or CocoaPods.



Installation via Swift Package Manager

Add it to Package.swift or via Xcode: File → Add Packages → enter URL: https://github.com/tadija/AEXML.git



Example: Reading XML



import AEXML

func parseWithAEXML(xmlString: String) -> [String: String]? { do { let xmlDoc = try AEXMLDocument(xml: xmlString) let root = xmlDoc.root

// Get element value let name = root["user"]["name"].value ?? "" let age = root["user"]["age"].value ?? ""

// Access by attribute let id = root["user"].attributes["id"] ?? ""

return ["id": id, "name": name, "age": age] } catch { print("Parsing error: \\(error)") return nil }}

// Example XMLlet xmlData = """<root> <user id="42"> <name>Ivan Petrov</name> <age>30</age> </user></root>"""if let result = parseWithAEXML(xmlString: xmlData) { print(result) // ["id": "42", "name": "I

Recommendations