11.Swift XML解析

11.Swift XML解析

  • Swift XML解析
    • XML数据解析
    • XML解析选择题

XML数据解析

在IOS中,提供了一套解析XML数据的API。其实也很简单,就是NSXMLParserNSXMLParserDelegate

可以直接指定到XML的URL去实例化NSXMLParser
public convenience init?(contentsOfURL url: NSURL)

解析文件,返回的是一次解析的结果
NSXMLParser.parse() -> Bool

监听解析节点的属性
NSXMLParserDelegate.parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])

监听解析节点的内容
NSXMLParserDelegate.parser(parser: NSXMLParser, foundCharacters string: String)

待解析的XML文件:

<data>
    <code value="1.0">
        <version>1.0.1</version>
    </code>
    <response>
        <info>Save you from anything</info>
    </response>
</data>

ViewController.swift

class ViewController: UIViewController,NSXMLParserDelegate {

    var currentNodeName:String!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // 实例化NSXMLParser
        let parse:NSXMLParser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("data", ofType: "xml")!))!
        parse.delegate = self
        // 开始解析
        parse.parse()

    }

    // 监听解析节点的属性
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){
        // 保存当前的解析到的节点名称
        self.currentNodeName = elementName
        if(elementName == "code"){
            // 获取code节点下 value属性的内容
            if let value = attributeDict["value"]{
                NSLog("value: \(value)")
            }
        }
    }

    // 监听解析节点的内容
    func parser(parser: NSXMLParser, foundCharacters string: String) {
        var content = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        if(content != "" && self.currentNodeName == "info"){
            NSLog("\(content)")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

XML解析选择题

这里再介绍一个关于NSXMLParserDelegate的API。

解析成功,并且解析结束时
NSXMLParserDelegate.parserDidEndDocument(parser: NSXMLParser)

questions.xml

<questions>
    <question text="1+1=?" right="C">
        <answer text="0" tag="A"></answer>
        <answer text="1" tag="B"></answer>
        <answer text="2" tag="C"></answer>
        <answer text="3" tag="D"></answer>
    </question>
</questions>

Question.swift

class Question: NSObject {
    var question:String!
    var right:String!
    var answerA:String!
    var answerB:String!
    var answerC:String!
    var answerD:String!
}

Main.storyboard

11.Swift XML解析_第1张图片

ViewController.swift

class ViewController: UIViewController,NSXMLParserDelegate {

    @IBOutlet weak var question: UILabel!
    @IBOutlet weak var answerA: UILabel!
    @IBOutlet weak var answerB: UILabel!
    @IBOutlet weak var answerC: UILabel!
    @IBOutlet weak var answerD: UILabel!
    @IBOutlet weak var inputTV: UITextField!
    @IBOutlet weak var hint: UILabel!

    var parser:NSXMLParser!
    // 用于保存全部题目
    var questions:Array<Question> = []

    // 用于保存当前解析到的题目
    var currentQuestion:Question!

    // 用于保存当前显示的题目
    var currentShowQuestion:Question!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // 实例化NSXMLParser
        self.parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("questions", ofType: "xml")!))
        self.parser.delegate = self
        // 开始解析
        self.parser.parse()
    }

    // 监听解析节点的属性
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        switch elementName{
            case "question":
                // 保存当前到的题目
                self.currentQuestion = Question()

                // 读取question节点下的 text属性值
                self.currentQuestion.question = attributeDict["text"]! as String

                // 读取question节点下的 right属性值
                self.currentQuestion.right = attributeDict["right"]! as String
                self.questions.append(self.currentQuestion)
                break
            case "answer":
                // 读取question节点下的 tag属性值
                let tag = attributeDict["tag"]! as String
                // 读取question节点下的 text属性值
                let text = attributeDict["text"]! as String

                // 设置当前到的题目的全部答案内容
                switch tag{
                    case "A":
                        self.currentQuestion.answerA = "\(tag):\(text)"
                        break
                    case "B":
                        self.currentQuestion.answerB = "\(tag):\(text)"
                        break
                    case "C":
                        self.currentQuestion.answerC = "\(tag):\(text)"
                        break
                    case "D":
                        self.currentQuestion.answerD = "\(tag):\(text)"
                        break
                    default :
                        break
                }
                break
            default :
                break
        }
    }

    // 监听解析成功并且结束时
    func parserDidEndDocument(parser: NSXMLParser) {
        self.currentShowQuestion = self.questions[0]
        self.question.text = self.currentShowQuestion.question
        self.answerA.text = self.currentShowQuestion.answerA
        self.answerB.text = self.currentShowQuestion.answerB
        self.answerC.text = self.currentShowQuestion.answerC
        self.answerD.text = self.currentShowQuestion.answerD
    }

    // 提交答案监听
    @IBAction func submitOnClicked(sender: AnyObject) {
        if let t:String = self.inputTV.text{
            let result = t.uppercaseString
            if(result == self.currentShowQuestion.right){
                self.hint.text = "正确"
            }else if (result == ""){
                self.hint.text = "输入不合法"
            }else {
                self.hint.text = "不正确"
            }
        }else{
            self.hint.text = "输入不合法"
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

你可能感兴趣的:(ios,xml,数据,api,url)