Detailed introduction to XML parsing

Source: Internet
Author: User
Author: arurknopper, original article link. Original article date: Translator: pucca; proofreaders: Cwift; FINAL: CMB this tutorial uses the NSXMLParser object to parse xml files. The parsing result is displayed in TableView. This tutorial uses the NSXMLParser object to parse the xml file based on ios9... on Xcode7.3.1. The parsing result is displayed in Table View. This tutorial is based on iOS 9.3 in Xcode 7.3.1.
Open Xcode and create a new single-window application. The name is IOS9XMLParserTutorial, and the organization name and organization ID are set by yourself. Select Swift as the language and iPhone as the device.

Open Books. xml and replace it with the following code:

 
     
          
   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    
  
 

Select iOS-> Source-> Swift File to add a new File as the data model of different items in the xml File. We call it Book. swift and replace it with the following code:

import Foundationclass Book {    var bookTitle: String = String()    var bookAuthor: String = String()}

Go to the tableViewController. swift file and add the following variables.

var books: [Book] = []var eName: String = String()var bookTitle = String()var bookAuthor = String()

Rewrite the viewDidLoad method

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()        }    }}

The NSXMLParser object parses the books. xml file in the bundle. Add the following table View data sources and delegation methods

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}

The title and author data of all books are saved in the books array and presented by Table View. Next, implement the NSXMLParser delegate method.

// 1func 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)    }}    // 3func 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        }    }}
  1. This method encounters" "Triggered when the start tag

  2. This method encounters" "Triggered when the end tag

  3. The parsing process is actually executed here. The title and author tags are parsed and the corresponding variables are initialized.

Build and runProject. You can view the titles and authors of all books in TableViewController.

The above is a detailed description of XML parsing (text). For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.