Implement the tutorial for parsing XML data in iOS App using Swift

  • 2020-05-13 03:32:31
  • OfStack

In IOS, a set of API that parses XML data is provided. It's actually very simple, NSXMLParser and NSXMLParserDelegate.

You can specify NSXMLParser directly to URL of XML to instantiate NSXMLParser


public convenience init?(contentsOfURL url: NSURL)

Parse the file and return the result of one parse

NSXMLParser.parse() -> Bool

Listen for the properties of the parse node

NSXMLParserDelegate.parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])

Listen for the contents of the parse node

NSXMLParserDelegate.parser(parser: NSXMLParser, foundCharacters string: String)

Example:

Here is the basic xml data parsing and printing.

1. Prepare xml data
Open notepad and write:


<?xml version="1.0" encoding="utf-8" ?>
<students>
  <student id="001">
      <name>Bill Gates</name>
      <age>15</age>
  </student>
  <student id="002">
      <name>Tim Cook</name>
      <age>18</age>
  </student>
</students>

Save and name it data.xml.

2. Analytical xml
Create a new project in Xcode, import data.xml into the new project, and drag it directly into it. Write the following code in ViewController.swift:


class ViewController: UIViewController,NSXMLParserDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()
        let parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("data", ofType: "xml")!))
        //1
        parser!.delegate = self
        parser!.parse()
    }     var currentNodeName:String!
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        currentNodeName = elementName
        if elementName == "student"{
            if let id = attributeDict["id"]{
            print("id:\(id)")
            }
        }
    }     func parser(parser: NSXMLParser, foundCharacters string: String) {
        //2
        let str = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        if str != "" {
            print("\(currentNodeName):\(str)")
        }
    }     override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Code comments:
1. NSXMLParserDelegate agent is required to use NSXMLParser
2. Remove the print as < student > The label, if written directly

func parser(parser: NSXMLParser, foundCharacters string: String) {
       print("\(string):\(str)")
 }

The previous label will be printed.

3. Code running results


id:001
name:Bill Gates
age:15
id:002
name:Tim Cook
age:18


Related articles: