Swift xml解析器导致错误

时间:2017-06-22 20:25:10

标签: xml swift

我正在尝试解析一个简单的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文件?我没有看到任何问题。

1 个答案:

答案 0 :(得分:0)

首先,为了从Bundle的内容中读取文件,请执行以下操作:

    let parser = QuizXMLParser()
    if let path = Bundle.main.url(forResource: "mathQuiz", withExtension: "xml") {
        parser.beginParsing(file: path)
    }

然后更改函数beginParsing(file url:String)以接受URL而不是String。

public func beginParsing(file url: URL) {
    guard let parser = XMLParser(contentsOf: 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)")
    }
}

这可以解决您的问题。