Swift解析XML教程
本教程使用 NSXMLParser 對象對 xml 文件進行解析。解析結果由 Table View 展示。本教程在 Xcode 7.3.1 上基于 iOS 9.3 構建。
打開 Xcode 并且新建一個單視窗應用。名字就叫 IOS9XMLParserTutorial,組織名字和組織標識自己定。語言選 Swift,設備只選 iPhone。
把 View Controller 從 Storyboard 中移除,并拖一個 Navigation Controller 到空的畫板里。這個 Navigation Controller 會自動攜帶一個 Table View Controller。當你把初始的 View Controller 刪除時相應的故事板起點也被移除了。所以我們先選中新添加的 Navigation Controller 在 Attribute Inspector 的 “Is Initial View Controller” 復選框打上勾作為新的故事板起點。
雙擊 able View Controller 的 Title Bar 將其設置為 “Books”。選擇 Table View Cell 然后在 Attributes Inspector 中將它的 Style 屬性設為 Subtitle。
Storyboard 長這樣
既然我們刪除了初始 View Controller ,ViewController.swift 也可以一起刪除了。選擇 iOS->Source->Cocoa Touch Class 添加一個新的文件,命名為 TableViewController,并且設置它為 UITableViewController 的子類。
前往 Storyboard 中選中 Table View Controller,在 Identity inspector 中將 Custom Class 部分設置為 TableViewController。
選擇 iOS->Source->Swift File,添加一個新的文件。命名為 Books.xml
打開 Books.xml 替換成以下代碼
<?xml version="1.0"?>
<catalog>
<book id="1">
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
</book>
<book id="2">
<title>1984</title>
<author>George Orwell</author>
</book>
<book id="3">
<title>The Lord of the Rings</title>
<author>J.R.R Tolkien</author>
</book>
<book id="4">
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
</book>
<book id="5">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>
</catalog>
選擇 iOS->Source->Swift File 添加新的文件作為 xml 文件中不同項的數據模型。我們叫它 Book.swift,并替換成以下代碼
import Foundation
class Book {
var bookTitle: String = String()
var bookAuthor: String = String()
}
前往 tableViewController.swift 文件,添加以下變量。
var books: [Book] = []
var eName: String = String()
var bookTitle = String()
var bookAuthor = String()
將 viewDidLoad 方法復寫為
override func viewDidLoad() {
super.viewDidLoad()
if let path = NSBundle.mainBundle().URLForResource("books", withExtension: "xml") {
if let parser = NSXMLParser(contentsOfURL: path) {
parser.delegate = self
parser.parse()
}
}
}
NSXMLParser 對象解析 bundle 中的 books.xml 文件。添加以下 table View 的數據源及委托方法
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let book = books[indexPath.row]
cell.textLabel?.text = book.bookTitle
cell.detailTextLabel?.text = book.bookAuthor
return cell
}
所有書的標題和作者數據會保存在 books 數組中并且由 Table View 呈現。接著,實現 NSXMLParser 的委托方法。
// 1
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
eName = elementName
if elementName == "book" {
bookTitle = String()
bookAuthor = String()
}
}
// 2
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "book" {
let book = Book()
book.bookTitle = bookTitle
book.bookAuthor = bookAuthor
books.append(book)
}
}
// 3
func parser(parser: NSXMLParser, foundCharacters string: String) {
let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if (!data.isEmpty) {
if eName == "title" {
bookTitle += data
} else if eName == "author" {
bookAuthor += data
}
}
}
- 該方法在解析對象碰到 “\ “ 的起始標簽時出觸發
- 該方法在解析對象碰到 “\ “ 的結尾標簽時出觸發
- 這里解析過程真正執行。標題和作者標簽會被解析并且相應的變量將會初始化。
構建并運行項目。在 TableViewController 中能看到所有書的標題和作者。
來自:http://swift.gg/2017/01/17/parsing-xml-tutorial/