Swift解析XML教程

xme007 7年前
   <p>本教程使用 NSXMLParser 对象对 xml 文件进行解析。解析结果由 Table View 展示。本教程在 Xcode 7.3.1 上基于 iOS 9.3 构建。</p>    <p>打开 Xcode 并且新建一个单视窗应用。名字就叫 IOS9XMLParserTutorial,组织名字和组织标识自己定。语言选 Swift,设备只选 iPhone。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0e8348777ca7808a8a47be4ea5a89132.png"></p>    <p>把 View Controller 从 Storyboard 中移除,并拖一个 Navigation Controller 到空的画板里。这个 Navigation Controller 会自动携带一个 Table View Controller。当你把初始的 View Controller 删除时相应的故事板起点也被移除了。所以我们先选中新添加的 Navigation Controller 在 Attribute Inspector 的 “Is Initial View Controller” 复选框打上勾作为新的故事板起点。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/af6df0f6f29e67ab1df6fe375c843c1b.png"></p>    <p>双击 able View Controller 的 Title Bar 将其设置为 “Books”。选择 Table View Cell 然后在 Attributes Inspector 中将它的 Style 属性设为 Subtitle。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/bec435479af2ae5586f32550e3a2e83f.png"></p>    <p>Storyboard 长这样</p>    <p><img src="https://simg.open-open.com/show/f3b8152ca297f69863be9e7d36003fef.png"></p>    <p>既然我们删除了初始 View Controller ,ViewController.swift 也可以一起删除了。选择 iOS->Source->Cocoa Touch Class 添加一个新的文件,命名为 TableViewController,并且设置它为 UITableViewController 的子类。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0d73b0573a5f2443572c4bf4e411da29.png"></p>    <p>前往 Storyboard 中选中 Table View Controller,在 Identity inspector 中将 Custom Class 部分设置为 TableViewController。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/5c564e3bffd3111aadbb996f0e688572.png"></p>    <p>选择 iOS->Source->Swift File,添加一个新的文件。命名为 Books.xml</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/34f8921a75fa92e473124ff0d4780f7d.png"></p>    <p>打开 Books.xml 替换成以下代码</p>    <pre>  <code class="language-swift"><?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>  </code></pre>    <p>选择 iOS->Source->Swift File 添加新的文件作为 xml 文件中不同项的数据模型。我们叫它 Book.swift,并替换成以下代码</p>    <pre>  <code class="language-swift">import Foundation    class Book {      var bookTitle: String = String()      var bookAuthor: String = String()  }  </code></pre>    <p>前往 tableViewController.swift 文件,添加以下变量。</p>    <pre>  <code class="language-swift">var books: [Book] = []  var eName: String = String()  var bookTitle = String()  var bookAuthor = String()  </code></pre>    <p>将 viewDidLoad 方法复写为</p>    <pre>  <code class="language-swift">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()          }      }  }  </code></pre>    <p>NSXMLParser 对象解析 bundle 中的 books.xml 文件。添加以下 table View 的数据源及委托方法</p>    <pre>  <code class="language-swift">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  }  </code></pre>    <p>所有书的标题和作者数据会保存在 books 数组中并且由 Table View 呈现。接着,实现 NSXMLParser 的委托方法。</p>    <pre>  <code class="language-swift">// 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          }      }  }  </code></pre>    <ol>     <li>该方法在解析对象碰到 “\ “ 的起始标签时出触发</li>     <li>该方法在解析对象碰到 “\ “ 的结尾标签时出触发</li>     <li>这里解析过程真正执行。标题和作者标签会被解析并且相应的变量将会初始化。</li>    </ol>    <p>构建并运行项目。在 TableViewController 中能看到所有书的标题和作者。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/582f27f696d45d039485a12ddbb4d51d.png"></p>    <p> </p>    <p> </p>    <p>来自:http://swift.gg/2017/01/17/parsing-xml-tutorial/</p>    <p> </p>