0
我試圖解析一個簡單的XML文件,但我不斷收到錯誤斯威夫特XML解析器導致錯誤
「錯誤描述:(可可錯誤-1)操作無法完成 行號:0"
XML文件(名爲mathquiz.xml放置在一個文件夾,名爲IMG):
<quiz>
<title>
Y1 Maths Quiz
</title>
<question>
<description>
What is 2+2
</description>
<answer>
4
</answer>
<answer>
3
</answer>
<answer>
2
</answer>
<answer>
1
</answer>
</question>
</quiz>
分析器:
//
// QuizXMLParser.swift
// MathQuiz
//
// Created by Raees on 22/06/2017.
// Copyright © 2017 Raees Apps. All rights reserved.
//
import Foundation
public class QuizXMLParser : NSObject, XMLParserDelegate {
var currentContent = ""
var quiz = Quiz()
var question = Question()
public func beginParsing(file url: String) {
guard let myURL = NSURL(string:url) else {
print("URL not defined properly")
return
}
guard let parser = XMLParser(contentsOf: myURL as URL) else {
print("Cannot Read Data")
return
}
parser.delegate = self
if !parser.parse(){
print("Data Errors Exist:")
let error = parser.parserError!
print("Error Description:\(error.localizedDescription)")
print("Line number: \(parser.lineNumber)")
}
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){
print("Beginning tag: <\(elementName)>")
if elementName == "question" {
question = Question()
}
currentContent = ""
}
public func parser(_ parser: XMLParser, foundCharacters string: String){
currentContent += string
print("Added to make \(currentContent)")
}
public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){
print("ending tag: </\(elementName)> with contents:\(currentContent)")
switch elementName{
case "question":
quiz.questions.append(question)
print ("model has \(question)")
case"title":
quiz.title = currentContent
case "description":
if let index = Int(currentContent) {
quiz.currentQuestionIndex = index
}
case "answer":
question.answers.append(currentContent)
default:
return
}
}
}
呼叫在視圖控制器解析器:
let parser = QuizXMLParser()
parser.beginParsing(file: "img/mathquiz.xml")
我怎樣才能使它成功地解析XML文件?我沒有看到任何問題。
XML文件應該以'<?xml version =「1.0」encoding =「UTF-8」?>'開頭。 – rmaddy
爲什麼使用'NSURL'而不是'URL'? – rmaddy
我正在關注makeapppie.com上的xml教程,並使用NSURL。生病改變它 –