gpt4 book ai didi

xml - 在 Swift 4 中解析 XML

转载 作者:搜寻专家 更新时间:2023-10-31 22:18:51 26 4
gpt4 key购买 nike

我是 Swift 中 XML 解析的新手,我在 Parsing XML from URL in Swift 上找到了这段代码但是当我尝试运行代码时出现了 EXC_BAD_INSTRUCTION 错误。错误描述如下:fatal error: expectedly found nil while unwrapping an Optional value

这是我的简单 XML 文件:

<xml>
<book>
<title>Book Title</title>
<author>Book Author</author>
</book>
</xml>

以下代码创建一个 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)
}

在这里,我实现了 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

}

currentDictionary 附加到 results 字典时,在 didEndElement 方法上发现错误。

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

}
}

请帮我解决这个问题。我使用的是在 Parsing XML from URL in Swift 上提供的完全相同的代码他们似乎没有任何问题。我做错了什么吗?

最佳答案

您的代码实际上从未初始化results,因此您第一次尝试使用它时,您正在尝试强制展开一个nil 可选值。那很糟。并且没有理由将其声明为隐式展开的可选。

你需要改变:

var results: [[String: String]]!

到:

var results = [[String: String]]()

您还需要删除该行:

results = nil

来自您的parser(_:parseErrorOccurred:) 方法。

如果您希望results 是可选的,那么您可以对代码进行以下更改:

results 的声明更改为:

var results: [[String: String]]? = [[String: String]]()

改变:

results.append(currentDictionary)

到:

results?.append(currentDictionary)

然后您将 results = nil 行留在 parser(_:parseErrorOccurred:) 中。

关于xml - 在 Swift 4 中解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46181106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com