Getting Started

Parse a Book Catalogue

In this tutorial you parse an XML book catalogue, navigate its tree structure, and extract element content using SwiftLibXML.

The approach shown here works unchanged on macOS, Linux, and Windows.

10 mins Estimated Time

Section 1

Parse the Document

Start by defining the XML source, wrapping it in Data, and passing it to XMLDocument.

The initialiser is failable: it returns nil when libxml2 cannot salvage the input even with error recovery enabled. Handling this with guard gives you a safe entry point into the rest of the code.

Step 1

Import Foundation and SwiftLibXML, then define the XML source as a multi-line string.

Catalogue.swift
1import Foundation
2
3func parseCatalogue() {
4 let xml = """
5 <?xml version="1.0" encoding="UTF-8"?>
6 <catalogue>
7 <book id="1">
8 <title>Clean Code</title>
9 <author>Robert C. Martin</author>
10 </book>
11 <book id="2">
12 <title>The Swift Programming Language</title>
13 <author>Apple Inc.</author>
14 </book>
15 </catalogue>
16 """
17}

Step 2

Wrap the source in Data and parse it with XMLDocument.

Because the target also imports Foundation, qualify the type as SwiftLibXML.XMLDocument to avoid the name clash with Foundation.XMLDocument.

Catalogue.swift
1import Foundation
2
3func parseCatalogue() {
4 let xml = """
5 <?xml version="1.0" encoding="UTF-8"?>
6 <catalogue>
7 <book id="1">
8 <title>Clean Code</title>
9 <author>Robert C. Martin</author>
10 </book>
11 <book id="2">
12 <title>The Swift Programming Language</title>
13 <author>Apple Inc.</author>
14 </book>
15 </catalogue>
16 """
17
18 guard let document = XMLDocument(data: Data(xml.utf8)) else { return }
19
20 let root = document.rootElement
21 print(root.name) // catalogue
22}

Query a Document with XPath

In this tutorial you compile XPath expressions to select elements, use predicates to narrow results, and query namespace-prefixed XML.