GitHub

SkipXML provides an XML document parser and in-memory tree representation for Skip apps. It parses XML data into XMLNode structures that can be queried, traversed, modified, and serialized back to XML strings.

On Darwin platforms (iOS, macOS) and in compiled Skip Fuse mode for Android, SkipXML uses Foundation's XMLParser and XMLParserDelegate for parsing. In transpiled Skip Lite mode, the Swift source is transpiled to Kotlin, and parsing is handled by the Java javax.xml.parsers.SAXParser and org.xml.sax.helpers.DefaultHandler APIs to provide equivalent functionality. The resulting XMLNode tree API is identical across both platforms.

Setup

Add the dependency to your Package.swift file:

.package(url: "https://source.skip.tools/skip-xml.git", from: "1.0.0")

And add the product to your target:

.target(name: "MyTarget", dependencies: [
    .product(name: "SkipXML", package: "skip-xml")
])

Usage

Parsing XML

Parse XML from Data or directly from a String:

import SkipXML
let xml = """
<library>
    <book id="1">
        <title>Swift Programming</title>
        <author>Apple</author>
    </book>
    <book id="2">
        <title>Kotlin in Action</title>
        <author>JetBrains</author>
    </book>
</library>
"""
let doc = try XMLNode.parse(string: xml)

The returned XMLNode is the document root. Access the top-level element with elementChildren:

let library = doc.elementChildren[0] // the <library> element

Querying Elements

Find child elements by name:

let books = library.childElements(named: "book") // all <book> children
let firstBook = library.firstChildElement(named: "book") // first <book> or nil

Search recursively through all descendants:

"let allTitles = library.descendants(named: "title") // finds

Read the original on github.com ↗