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.
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.
property to Subtitle in the Attributes Inspector.
Class Add a new file, name it TableViewController, and set it as a subclass of UITableViewController.
File and add a new file. Name it 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>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
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 } } }
- This method is triggered when the parsing object encounters the start tag of "
" - This method is triggered when the parsing object encounters When the end tag of "
" is encountered, it is triggered. - 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.
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!

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

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

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

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

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)

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

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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 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
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
