Home >Backend Development >XML/RSS Tutorial >Detailed introduction to XML parsing (graphics and text)

Detailed introduction to XML parsing (graphics and text)

黄舟
黄舟Original
2017-03-17 17:22:091774browse

This tutorial uses NSXMLParser Object to parse xml files. The parsing results are displayed by Table View. This tutorial is built on iOS 9.3 on Xcode 7.3.1.
Open Xcode and create a new single-window application. The name is IOS9XMLParserTutorial, and the organization name and organization logo are determined by yourself. Select Swift as the language and iPhone as the device.

Detailed introduction to XML parsing (graphics and text)

Remove the View Controller from the Storyboard and drag a Navigation Controller to the empty artboard. This Navigation Controller will automatically carry a Table View Controller. When you delete the initial View Controller the corresponding storyboard starting point is also removed. So we first select the newly added Navigation Controller and tick the "Is Initial View Controller" checkbox in the Attribute Inspector as the starting point of the new storyboard.

Detailed introduction to XML parsing (graphics and text)

Double-click the able View Controller's Title Bar to set it to "Books". Select the Table View Cell and set its Style

property to Subtitle in the Attributes Inspector.

Detailed introduction to XML parsing (graphics and text)

Storyboard looks like this

Detailed introduction to XML parsing (graphics and text)

Now that we have deleted the initial View Controller, ViewController.swift can also be deleted together. Select iOS->Source->Cocoa Touch

Class Add a new file, name it TableViewController, and set it as a subclass of UITableViewController.

Detailed introduction to XML parsing (graphics and text)

Go to the Storyboard, select the Table View Controller, and set the Custom Class section to TableViewController in the Identity inspector.

Detailed introduction to XML parsing (graphics and text)

Select iOS->Source->Swift

File and add a new file. Name it Books.xml

Detailed introduction to XML parsing (graphics and text)

Open Books.xml and replace it with the following code

<?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>

Select iOS->Source->Swift File to add a new file Data

Model as different items in an xml file. Let’s call it Book.swift and replace it with the following code

import Foundation

class 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 viewDi

dLoad method as

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 object to parse the books.xml file in the bundle. Add the following table View data source and delegate method

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 will be saved in the books

array and presented by the Table View. Next, implement the delegate method of 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
        }
    }
}

  1. This method is triggered when the parsing object encounters the start tag of ""

  2. This method is triggered when the parsing object encounters When the end tag of "" is encountered, it is triggered.

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

Build and run the project. You can see the titles and authors of all books in the TableViewController.
Detailed introduction to XML parsing (graphics and text)


The above is the detailed content of Detailed introduction to XML parsing (graphics and text). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn