iOS tutorial 7:解析XML(swift)

参考:Parsing XML Tutorial

使用XMLParser解析XML文件,然后用table展示数据。

  • Single View Application模板新建项目XMLParserTutorial
  • 删除SB中的View Controller,拖进一个Navigation Controller。选择新的View Controller为 "Is Initial View Controller"。设置Navigation Bar的title为Books
  • 新建一个继承至UITableViewController,名为TableViewController的控制器文件,并与SB的控制器关联。
  • 新建一个xml文件Books.xml,用于之后解析,文件内容为:


    
        To Kill a Mockingbird
        Harper Lee
    
    
        1984
        George Orwell
    
    
        The Lord of the Rings
        J.R.R Tolkien
    
    
        The Catcher in the Rye
        J.D. Salinger
    
    
        The Great Gatsby
        F. Scott Fitzgerald
    

  • 新建一个文件 Book.swift
import Foundation

class Book {
    var bookTitle: String = ""
    var bookAuthor: String = ""
}
  • TableViewController中添加几个变量:
    var books: [Book] = []
    var eName: String = ""
    var bookTitle = ""
    var bookAuthor = ""
  • viewDidLoad方法中,添加读取XMl文件代码:
    override func viewDidLoad() {
        super.viewDidLoad()

        if let path = Bundle.main.url(forResource: "Books", withExtension: "xml") {
            if let parser = XMLParser(contentsOf: path) {
                parser.delegate = self
                parser.parse()
            }
        }
  • 添加Table View的数据源代理方法:
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return books.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        
        let book = books[indexPath.row]
        cell.textLabel?.text = book.bookTitle
        cell.detailTextLabel?.text = book.bookAuthor

        return cell
    }
  • TableViewController采纳XMLParserDelegate协议:

    class TableViewController: UITableViewController, XMLParserDelegate 
    
  • 实现XMLParserDelegate中的三个方法:

    // 解析XMl元素开始时
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        print("开始 \(elementName)")
        eName = elementName
        if elementName == "book" {
            bookTitle = ""
            bookAuthor = ""
        }
    }
    // 正在解析XMl元素
    func parser(_ parser: XMLParser, foundCharacters string: String) {
        print("ing \(eName)")
        let data = string.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        
        if (!data.isEmpty) {
            if eName == "title" {
                bookTitle += data
            } else if eName == "author" {
                bookAuthor += data
            }
        }
    }
    // 结束解析XMl元素
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        print("结束 \(elementName)")
        if elementName == "book" {
            
            let book = Book()
            book.bookTitle = bookTitle
            book.bookAuthor = bookAuthor
            
            books.append(book)
        }
    }

三个方法分别在XMl元素开始解析、正在解析、结束解析时调用,也就是说有很多元素时就不停在调用这三个方法。

iOS tutorial 7:解析XML(swift)_第1张图片

代码

XMLParserTutorial

你可能感兴趣的:(iOS tutorial 7:解析XML(swift))