Ric*_*cky 4 xml xml-parsing swift
我是 Swift 中 XML 解析的新手,我在从 Swift 中的 URL 解析 XML上找到了这段代码,但是EXC_BAD_INSTRUCTION当我尝试运行代码时出现错误。错误描述如下:fatal error: unexpectedly found nil while unwrapping an Optional value
这是我的简单 XML 文件:
<xml>
<book>
<title>Book Title</title>
<author>Book Author</author>
</book>
</xml>
Run Code Online (Sandbox Code Playgroud)
以下代码创建一个XMLParser对象并解析位于我的文档中的 XML 文件。
// get xml file path from Documents and parse
let filePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last?.appendingPathComponent("example.xml")
let parser = XMLParser(contentsOf: filePath!)
parser?.delegate = self
if (parser?.parse())! {
print(self.results)
}
Run Code Online (Sandbox Code Playgroud)
在这里,我实现了这些XMLParserDelegate方法并定义了我的字典:
// a few constants that identify what element names we're looking for inside the XML
let recordKey = "book"
let dictionaryKeys = ["title","author"]
// a few variables to hold the results as we parse the XML
var results: [[String: String]]! // the whole array of dictionaries
var currentDictionary: [String: String]! // the current dictionary
var currentValue: String? // the current value for one of the keys in the dictionary
// start element
//
// - If we're starting a "record" create the dictionary that will hold the results
// - If we're starting one of our dictionary keys, initialize `currentValue` (otherwise leave `nil`)
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementName == recordKey {
currentDictionary = [String : String]()
} else if dictionaryKeys.contains(elementName) {
currentValue = String()
}
}
// found characters
//
// - If this is an element we care about, append those characters.
// - If `currentValue` still `nil`, then do nothing.
func parser(_ parser: XMLParser, foundCharacters string: String) {
currentValue? += string
}
// end element
//
// - If we're at the end of the whole dictionary, then save that dictionary in our array
// - If we're at the end of an element that belongs in the dictionary, then save that value in the dictionary
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == recordKey {
results.append(currentDictionary)
currentDictionary = nil
} else if dictionaryKeys.contains(elementName) {
currentDictionary[elementName] = currentValue
currentValue = nil
}
}
// Just in case, if there's an error, report it. (We don't want to fly blind here.)
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print(parseError)
currentValue = nil
currentDictionary = nil
results = nil
}
Run Code Online (Sandbox Code Playgroud)
将附加到字典didEndElement时在方法上发现错误。currentDictionaryresults
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == recordKey {
results.append(currentDictionary) // Line with Error
currentDictionary = nil
} else if dictionaryKeys.contains(elementName) {
currentDictionary[elementName] = currentValue
currentValue = nil
}
}
Run Code Online (Sandbox Code Playgroud)
请帮我解决这个问题。我正在使用在 Swift 中从 URL 解析 XML 中提供的完全相同的代码,它们似乎没有任何问题。我做错了什么吗?
您的代码从未真正初始化,results因此您第一次尝试使用它时,您是在尝试强制解包一个nil可选值。那很糟。并且没有理由将其声明为隐式解包的可选项。
你需要改变:
var results: [[String: String]]!
Run Code Online (Sandbox Code Playgroud)
到:
var results = [[String: String]]()
Run Code Online (Sandbox Code Playgroud)
您还需要删除该行:
results = nil
Run Code Online (Sandbox Code Playgroud)
从你的parser(_:parseErrorOccurred:)方法。
如果您宁愿results是可选的,那么您可以对代码进行以下更改:
将声明更改results为:
var results: [[String: String]]? = [[String: String]]()
Run Code Online (Sandbox Code Playgroud)
改变:
results.append(currentDictionary)
Run Code Online (Sandbox Code Playgroud)
到:
results?.append(currentDictionary)
Run Code Online (Sandbox Code Playgroud)
你把results = nil线路留在parser(_:parseErrorOccurred:).
| 归档时间: |
|
| 查看次数: |
20339 次 |
| 最近记录: |