parse xml in swift

To parse XML in Swift, you can use the XMLParser class. Here's a simple example of how to parse XML using XMLParser:

main.swift
import Foundation

class XMLParserDelegate: NSObject, XMLParserDelegate {
    // Variables to store the parsed data
    var currentValue: String?
    var parsedData: [String: String] = [:]
    
    // Start element tag
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        currentValue = ""
    }
    
    // Characters within an element
    func parser(_ parser: XMLParser, foundCharacters string: String) {
        currentValue?.append(string)
    }
    
    // End element tag
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if let value = currentValue {
            parsedData[elementName] = value
        }
        currentValue = nil
    }
}

// Example XML data
let xmlData = """
    <book>
        <title>Harry Potter</title>
        <author>J.K. Rowling</author>
        <genre>Fantasy</genre>
    </book>
    """.data(using: .utf8)

// Create an instance of XMLParser and set the delegate
let parser = XMLParser(data: xmlData!)
let delegate = XMLParserDelegate()
parser.delegate = delegate

// Start parsing the XML
if parser.parse() {
    // Access the parsed data
    print(delegate.parsedData)
}
1329 chars
46 lines

In this example, we have created a custom XMLParserDelegate class to handle the parsing of the XML. We implement the necessary delegate methods to handle start and end elements, as well as characters within an element. The parsed data is stored in a dictionary parsedData. Finally, we create an instance of XMLParser, set the delegate, and start parsing the XML data.

Note that this is a basic example, and you might need to modify it according to your XML structure and requirements.

related categories

gistlibby LogSnag