search
HomeBackend DevelopmentXML/RSS TutorialDetailed introduction to XML parsing (graphics and text)

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
How to Use RSS Feeds for News Aggregation and Content Curation?How to Use RSS Feeds for News Aggregation and Content Curation?Mar 10, 2025 pm 03:47 PM

This article explains how to use RSS feeds for efficient news aggregation and content curation. It details subscribing to feeds, using RSS readers (like Feedly and Inoreader), organizing feeds, and leveraging features for targeted content. The bene

How Can I Integrate XML and Semantic Web Technologies?How Can I Integrate XML and Semantic Web Technologies?Mar 10, 2025 pm 05:50 PM

This article explores integrating XML and Semantic Web technologies. The core issue is mapping XML's structured data to RDF triples for semantic interoperability. Best practices involve ontology definition, strategic mapping approaches, careful att

How Do I Use Atom Publishing Protocol for Web Content Management?How Do I Use Atom Publishing Protocol for Web Content Management?Mar 10, 2025 pm 05:48 PM

This article explains Atom Publishing Protocol (AtomPub) for web content management. It details using HTTP methods (GET, POST, PUT, DELETE) with Atom format for content creation, retrieval, updating, and deletion. The article also discusses AtomPub

How Do I Implement Content Syndication Using RSS?How Do I Implement Content Syndication Using RSS?Mar 10, 2025 pm 03:41 PM

This article details implementing content syndication using RSS feeds. It covers creating RSS feeds, identifying target websites, submitting feeds, and monitoring effectiveness. Challenges like limited control and rich media support are also discus

How Do I Use XML for Data Interoperability in Healthcare/Finance/etc.?How Do I Use XML for Data Interoperability in Healthcare/Finance/etc.?Mar 10, 2025 pm 05:50 PM

This article details using XML for data interoperability, focusing on healthcare and finance. It covers schema definition, XML document creation, data transformation, parsing, and exchange mechanisms. Key XML standards (HL7, DICOM, FinML, ISO 20022)

How Can I Secure RSS Feeds Against Unauthorized Access?How Can I Secure RSS Feeds Against Unauthorized Access?Mar 10, 2025 pm 03:42 PM

This article details securing RSS feeds against unauthorized access. It examines various methods including HTTP authentication, API keys with rate limiting, HTTPS, and content obfuscation (discouraged). Best practices involve IP restriction, revers

How Can I Create a Custom XML Vocabulary for My Domain?How Can I Create a Custom XML Vocabulary for My Domain?Mar 10, 2025 pm 05:48 PM

This article details creating custom XML vocabularies (schemas) for data consistency. It covers defining scope, identifying entities & attributes, designing XML structure, choosing a schema language (XSD or Relax NG), schema development, testing

How Can I Optimize RSS Feeds for SEO?How Can I Optimize RSS Feeds for SEO?Mar 10, 2025 pm 03:39 PM

This article explains how optimizing RSS feeds indirectly improves website SEO. It focuses on enhancing feed content (descriptions, keywords, metadata), structure (XML, formatting, encoding), and distribution to boost user engagement, content discov

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment