Cowboy Tech

iOS数据存储-XML

Start parse XML

注意要遵循协议NSXMLParserDelegate

class ViewController: UIViewController,NSXMLParserDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let filePath = NSBundle.mainBundle().pathForResource("data", ofType: "xml")!
        let fileUrl = NSURL(fileURLWithPath: filePath )
        let parser = NSXMLParser(contentsOfURL:fileUrl)

        parser!.delegate = self
        parser!.parse()

    }

Parse to get node and attribute

var currentNodeName:String!

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {      
    currentNodeName = elementName
    if elementName == "person" { 
        //需要判断,如果是空值的话,也不会报错
        if let age: AnyObject=attributeDict["age"]{
            print("age:\(age)")
        }
    }
}

Parse to get Value in node

//获得节点的实际内容
func parser(parser: NSXMLParser, foundCharacters string: String) {

    let str = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

    if str != ""{

        print("current node : \(currentNodeName), value: \(str)")
    }
}

剔除空格的字符串

let str = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

判断不为空

if str != ""{
    ...
}

Question Project

Qustion Model

class Question: NSObject {

var question:String!
var right:String!
var anwserA:String!
var anwserB:String!
var anwserC:String!
var anwserD:String!
}

Parse all node automatically without loop

var questions:Array<Question> = []    
var currentQuestion:Question!

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

    if elementName == "question" {

        currentQuestion = Question()
        questions.append(currentQuestion)
        currentQuestion.question = attributeDict["text"]! as String
        currentQuestion.right = attributeDict["right"]! as String

    } else if elementName == "anwser" {

        let tag = attributeDict["tag"]! as String

        if tag == "A"{
            currentQuestion.anwserA = attributeDict["text"]! as String
        }else if tag == "B"{
            currentQuestion.anwserB = attributeDict["text"]! as String
        }else if tag == "C"{
            currentQuestion.anwserC = attributeDict["text"]! as String
        }else if tag == "D"{
            currentQuestion.anwserD = attributeDict["text"]! as String
        }
    }
}

After Parse finish

func parserDidEndDocument(parser: NSXMLParser) {
...
}

Add new element to Array

questions.append(currentQuestion)

Judge if equal or not

if tag == "A"