我想解析本地xml文件中的数据,并使用文件中的信息填充表视图。我将schedule.xml文件添加到我的项目中,并编写了此代码
override func viewDidLoad() {
super.viewDidLoad()
let urlpath = NSBundle.mainBundle().pathForResource("scheduleFile", ofType: "xml")
let url:NSURL = NSURL.fileURLWithPath(urlpath!)
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.parse()
let success: Bool = parser.parse()
print(success)
}
我认为我的表视图有问题,但后来我添加了print(成功)并意识到我没有解析任何数据。日志给出了错误。有人能告诉我出了什么问题吗?
以下是完整代码:
import UIKit
class ClassListTableViewController: UITableViewController, NSXMLParserDelegate {
var parser = NSXMLParser()
var classList: [Class] = []
override func viewDidLoad() {
super.viewDidLoad()
let urlpath = NSBundle.mainBundle().pathForResource("scheduleFile", ofType: "xml")
let url:NSURL = NSURL.fileURLWithPath(urlpath!)
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.parse()
let success: Bool = parser.parse()
print(success)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return classList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ClassCell", forIndexPath: indexPath)
let oneClass: Class = classList[indexPath.row]
cell.textLabel?.text = oneClass.name
return cell
}
//MARK: - NSXMLParserDelegate methods
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
Class().eName = elementName
if elementName == "task" {
Class().name = String()
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if (!data.isEmpty) {
if Class().eName == "title" {
Class().name += data
print(Class().name)
}
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "task" {
let oneClass: Class = Class()
oneClass.name = Class().name
//oneClass.image = image
classList.append(oneClass)
}
}
}
这里的课程是数学,历史等。不要混淆。 谢谢!