分类 xml 下的文章

xml解析(DOM)

//
//  ViewController.swift
//  xml解析
//
//  Created by zhang on 16/2/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.decodeXML()
    }
    /**
     使用步骤
     First add the files from the Pod/Classes folder in this project to your source tree, then include them somewhere in your code,

     In Xcode choose the project file (in the project navigator, the top item).

     In the list choose your project target and select 'Build Settings' at the top of the window. Then you should see a list of build options.

     Add this line to 'Header Search Paths' (use search bar to find the right option) /usr/include/libxml2

     Add this line to 'Other Linker Flags': -lxml2
     */
    func decodeXML()
    {
        let url = NSURL(string: "http://localhost/videos.xml")
        let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in

            // 实例化GDataXMLDocument
            let xml:GDataXMLDocument! = try? GDataXMLDocument(data: data!)
            // 循环根节点的子节点
            for element in xml.rootElement().children()
            {
                let video = Video()
                // 循环数据节点的属性并完成赋值
                for videoElment in element.children()
                {
                    video.setValue(videoElment.stringValue, forKey: videoElment.name)
                }
                // 去除节点属性值对象数组
                let attrs = element.valueForKey("attributes")! as! [GDataXMLNode]
                // 完成对象属性的赋值
                for attr in attrs
                {
                    video.setValue(attr.stringValue(), forKey: attr.name())
                }
            }
        }
    }
    func useNSNumber()
    {
        let url = NSURL(string: "http://localhost/demo.json")
        let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            print(data)
            if data != nil
            {
                let json:AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
                let mes = Message()
                mes.setValuesForKeysWithDictionary(json as! [String : AnyObject])
                print(mes.valueForKey("messageId"))

            }
        }
    }
}
class Message:NSObject {
    // 数据类型为int的时候当服务器返回 null 的时候会抱下面的错误,用 NSNumber 就不会
    // this class is not key value coding-compliant for the key messageId
    var messageId:NSNumber!
    var message:String!
}
class Video:NSObject {
    var name:String!
    var length:String!
    var videoURL:String!
    var imageURL:String!
    var desc:String!
    var teacher:String!
    var videoId:String!
}

xml解析(SAX)

//
//  ViewController.swift
//  xml解析
//
//  Created by admin on 16/2/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UITableViewController,NSXMLParserDelegate {

    lazy var videos:[Video] = []
    lazy var nodeString:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.decodeXml()

    }
    @IBAction func decodeXml()
    {
        let url = NSURL(string: "http://test.com/videos.xml")
        // 忽略缓存数据
        let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { [weak self] (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            let xml = NSXMLParser(data: data!)
            xml.delegate = self
            xml.parse()
        }
    }
    // 开始解析文档
    func parserDidStartDocument(parser: NSXMLParser)
    {
        self.videos.removeAll()
    }

    // 开始节点
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        if elementName == "video"
        {
            self.videos.append(Video())
        }
        self.nodeString = ""
    }

    // 获得文本内容
    func parser(parser: NSXMLParser, foundCharacters string: String)
    {
        self.nodeString = "\(self.nodeString)\(string)"
    }
    // 结束节点
    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        if elementName != "video" && elementName != "videos"
        {
            self.videos[self.videos.count - 1].setValue(self.nodeString, forKey: elementName)
        }
    }
    // 结束解析文档
    func parserDidEndDocument(parser: NSXMLParser)
    {
        self.tableView.reloadData()
        self.refreshControl?.endRefreshing()
    }
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifer = "xmlCell"
        var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifer)
        if cell == nil
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifer)
        }
        cell.textLabel?.text = self.videos[indexPath.row].name
        cell.detailTextLabel?.text = self.videos[indexPath.row].videoURL
        return cell
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.videos.count
    }
}
class Video:NSObject {
    var name:String!
    var length:String!
    var videoURL:String!
    var imageURL:String!
    var desc:String!
    var teacher:String!
}