如何将数据写入xml文件?
也许有人知道swift 3等的XMLWriter?
我的游戏中有一个记分板,我想将int数据保存到项目中的xml文件中,我可以这样做吗?
在Objective C版本的XMLWriter中,我在会话时遇到错误。
更新1:
class XML: NSObject, XMLParserDelegate {
let xmlParser: XMLParser
var scores = [XMLData]()
var topData: XMLData?
var xmlText = ""
init(withXML xml: NSData) {
self.xmlParser = XMLParser(data: xml as Data)
}
func parse() -> [XMLData] {
xmlParser.delegate = self
xmlParser.parse()
return scores
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementName == "hightScore" {
topData = XMLData()
}
if elementName == "topOne" {
xmlText = ""
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "topOne" {
let text = xmlText.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if let topScore = Int(text) {
topData?.topScore = topScore
}
}
if elementName == "hightScore" {
if let hightScore = topData {
scores.append(hightScore)
}
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
xmlText += string
}
}
class XMLData: CustomStringConvertible {
var topScore = 0
var description: String {
return "\(topScore)"
}
}
和
func readXML() {
if let xmlUrl = Bundle.main.url(forResource: "Score", withExtension: "xml") {
do {
let xmlText = try String(contentsOf: xmlUrl)
if let xmlData = xmlText.data(using: String.Encoding.utf8) {
let parser = XML(withXML: xmlData as NSData)
for score in parser.parse() {
gameSetting.topScore = score.topScore
}
}
} catch {
print(error)
}
}
}