Swift学习笔记(2)网络数据交换格式(XML,JSON)解析 [iOS实战 入门与提高卷]

Swift学习笔记(2)网络数据交换格式(XML,JSON)解析 [iOS实战 入门与提高卷],第1张

概述Swift学习笔记(2)网络数据交换格式(XML,JSON)解析 参考书籍及资源:iOS实战 入门与提高卷 关东升 参考书籍地址 用NSXML来解析XML文档 用TBXML来解析XML文档 用NSJSONSerialization来解析JSON文档 目录 Swift学习笔记2网络数据交换格式XMLJSON解析 目录 用NSXML来解析XML文档 示例文档Notesxml 创建XMLParser类 Swift学习笔记(2)网络数据交换格式(XML,JsON)解析

参考书籍及资源:iOS实战 入门与提高卷 关东升 参考书籍地址

用NSXML来解析XML文档 用TBXML来解析XML文档 用NSJsONSerialization来解析JsON文档 目录 Swift学习笔记2网络数据交换格式XMLJSON解析 目录 用NSXML来解析XML文档 示例文档Notesxml 创建XMLParser类 调用与运行结果 用TBXML来解析XML文档 准备工作 创建XMLParser类 调用与运行结果 用NSJSONSerialization来解析JSON文档 示例文档 Notesdata 示例代码 运行结果 用NSXML来解析XML文档

NSXML是iOS SDK自带的,也是苹果默认的解析框架,框架的核心是NSXMLParser和它的委托协议NSXMLParserDelegate。

示例文档Notes.xml
<?xml version="1.0" enCoding="UTF-8"?><Notes>  <Note ID="1">    <cdate>2014-12-21</cdate>    <Content>早上8点钟到公司</Content>    <UserID>tony</UserID>  </Note>  <Note ID="2">    <cdate>2014-12-22</cdate>    <Content>发布iOSBook1</Content>    <UserID>tony</UserID>  </Note>  <Note ID="3">    <cdate>2014-12-23</cdate>    <Content>发布iOSBook2</Content>    <UserID>tony</UserID>  </Note>  <Note ID="4">    <cdate>2014-12-24</cdate>    <Content>发布iOSBook3</Content>    <UserID>tony</UserID>  </Note>  <Note ID="5">    <cdate>2014-12-25</cdate>    <Content>发布2016奥运会应用iPhone版本</Content>    <UserID>tony</UserID>  </Note>  <Note ID="6">    <cdate>2014-12-26</cdate>    <Content>发布2016奥运会应用iPad版本</Content>    <UserID>tony</UserID>  </Note></Notes>
创建XMLParser类
import Foundationclass XMLParser: NSObject,NSXMLParserDelegate {    private var notes:NSMutableArray! = []    private var currentTagname:String!    func startParse(){        NSLog("start parse")        let path=NSBundle.mainBundle().pathForResource("Notes",ofType: "xml")!        let url=NSURL(fileURLWithPath: path)        //开始解析        let parser=NSXMLParser(contentsOfURL: url)!        parser.delegate=self        parser.parse()    }    //文档开始时触发    func parserDIDStartdocument(parser: NSXMLParser) {        self.notes=NSMutableArray()    }    //文档出错时触发    func parser(parser: NSXMLParser,parseErrorOccurred parseError: NSError) {        NSLog("%@",parseError)    }    //遇到一个开始标签时触发,其中namespaceURI是命名空间,qualifIEdname是限定名,attributes是字典属性集合    func parser(parser: NSXMLParser,dIDStartElement elementname: String,namespaceURI: String?,qualifIEdname qname: String?,attributes attributeDict: [String : String]) {        self.currentTagname=elementname        if self.currentTagname == "Note"{            let ID=attributeDict["ID"]! as Nsstring            let dict=NSMutableDictionary()            dict.setobject(ID,forKey: "ID")            self.notes.addobject(dict)        }    }    //遇到字符串时触发    func parser(parser: NSXMLParser,foundCharacters string: String) {    //去除空格和回车        let s1 = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())        if s1 == ""{            return        }        let dict = self.notes.lastObject as! NSMutableDictionary        if (self.currentTagname == "cdate"){            dict.setobject(string,forKey: "cdate")        }        if (self.currentTagname == "Content"){            dict.setobject(string,forKey: "Content")        }        if (self.currentTagname == "UserID"){            dict.setobject(string,forKey: "UserID")        }    }    //遇到结束标签时触发    func parser(parser: NSXMLParser,dIDEndElement elementname: String,qualifIEdname qname: String?) {        self.currentTagname=nil    }    //文档结束时触发    func parserDIDEnddocument(parser: NSXMLParser) {        NSLog("end parse")        NSLog("\(notes)")    }}
调用与运行结果
overrIDe func vIEwDIDLoad() {        super.vIEwDIDLoad()        // Do any additional setup after loading the vIEw,typically from a nib. let parser=XMLParser() parser.startParse() } 
2016-05-17 12:03:42.836 XMLTest[61377:445073] start parse2016-05-17 12:03:42.852 XMLTest[61377:445073] end parse2016-05-17 12:03:42.853 XMLTest[61377:445073] (        {        cdate = "2014-12-21";        Content = "\U65e9\U4e0a8\U70b9\U949f\U5230\U516c\U53f8";        UserID = tony;        ID = 1;    },{        cdate = "2014-12-22";        Content = "\U53d1\U5e03iOSBook1";        UserID = tony;        ID = 2;    },{        cdate = "2014-12-23";        Content = "\U53d1\U5e03iOSBook2";        UserID = tony;        ID = 3;    },{        cdate = "2014-12-24";        Content = "\U53d1\U5e03iOSBook3";        UserID = tony;        ID = 4;    },{        cdate = "2014-12-25";        Content = "\U53d1\U5e032016\U5965\U8fd0\U4f1a\U5e94\U7528iPhone\U7248\U672c";        UserID = tony;        ID = 5;    },{        cdate = "2014-12-26";        Content = "\U53d1\U5e032016\U5965\U8fd0\U4f1a\U5e94\U7528iPad\U7248\U672c";        UserID = tony;        ID = 6;    })
用TBXML来解析XML文档

TBXML是第三方框架,使用起来比NSXML更简单。

准备工作

TBXML下载地址

下载完成后将TBXML-headers和TBXML-Code文件夹添加到工程中,并添加以下Framewok和库

在Xcode6以后的版本,需要创建Prefixheader.pch文件

并选择TARGETS->工程名->Buil Setting->Apple LLVM x.x Language ->Prefix header,输入Prefixheader.pch

在Prefixheader.pch中添加以下代码

#import <Foundation/Foundation.h>#define ARC_ENABLED

在桥接头文件中添加以下代码(关于桥接头文件请参考Swift和Objective-C的混编)

#import <Foundation/Foundation.h>#import "TBXML.h"
创建XMLParser类
import Foundationclass XMLParser: NSObject {    private var notes:NSMutableArray! = []    func startParse(){        NSLog("start parse")        self.notes=NSMutableArray()        let tbxml=(try? TBXML(XMLfile: "Notes.xml",error:()))!        //获取XML文档根元素        let root=tbxml.rootXMLElement        if root != nil{            //查找root元素下的Note元素            var noteElement=TBXML.childElementnamed("Note",parentElement: root)            while noteElement != nil{                let dict=NSMutableDictionary()                //查找Note元素下的cdate元素                let cdateElemet=TBXML.childElementnamed("cdate",parentElement: noteElement)                if cdateElemet != nil{                    let cdate=TBXML.textForElement(cdateElemet)                    dict.setValue(cdate,forKey: "cdate")                }                //查找Note元素下的Content元素                let ContentElemet=TBXML.childElementnamed("Content",parentElement: noteElement)                if ContentElemet != nil{                    let Content=TBXML.textForElement(ContentElemet)                    dict.setValue(Content,forKey: "Content")                }                //查找Note元素下的UserID元素                let UserIDElemet=TBXML.childElementnamed("UserID",parentElement: noteElement)                if UserIDElemet != nil{                    let UserID=TBXML.textForElement(UserIDElemet)                    dict.setValue(UserID,forKey: "UserID")                }                //获取Note元素的ID属性值                let ID=TBXML.valueOfAttributenamed("ID",forElement: noteElement)                dict.setValue(ID,forKey: "ID")                self.notes.addobject(dict)                //获取同层的下一个Note元素                noteElement=TBXML.nextSiblingnamed("Note",searchfromElement: noteElement)            }        }        NSLog("end parse")        NSLog("\(notes)")        self.notes=nil    }}
调用与运行结果

同上

用NSJsONSerialization来解析JsON文档

NSJsONSerialization是iOS 5之后苹果提供的API。

示例文档 Notes.data
{"ResultCode":0,"Record":[ {"ID":"1","cdate":"2014-12-23","Content":"发布iOSBook0","UserID":"tony"},{"ID":"2","cdate":"2014-12-24","Content":"发布iOSBook1",{"ID":"3","cdate":"2014-12-25","Content":"发布iOSBook2",{"ID":"4","cdate":"2014-12-26","Content":"发布iOSBook3",{"ID":"5","cdate":"2014-12-27","Content":"发布iOSBook4",{"ID":"6","cdate":"2014-12-28","Content":"发布iOSBook5",{"ID":"7","cdate":"2014-12-29","Content":"发布iOSBook6",{"ID":"8","cdate":"2014-12-30","Content":"发布iOSBook7",{"ID":"9","cdate":"2014-12-31","Content":"发布iOSBook8",{"ID":"10","cdate":"2014-12-32","Content":"发布iOSBook9",{"ID":"11","cdate":"2014-12-33","Content":"发布iOSBook10",{"ID":"12","cdate":"2014-12-34","Content":"发布iOSBook11",{"ID":"13","cdate":"2014-12-35","Content":"发布iOSBook12",{"ID":"14","cdate":"2014-12-36","Content":"发布iOSBook13",{"ID":"15","cdate":"2014-12-37","Content":"发布iOSBook14",{"ID":"16","cdate":"2014-12-38","Content":"发布iOSBook15",{"ID":"17","cdate":"2014-12-39","Content":"发布iOSBook16",{"ID":"18","cdate":"2014-12-40","Content":"发布iOSBook17",{"ID":"19","cdate":"2014-12-41","Content":"发布iOSBook18",{"ID":"20","cdate":"2014-12-42","Content":"发布iOSBook19",{"ID":"21","cdate":"2014-12-43","Content":"发布iOSBook20",{"ID":"22","cdate":"2014-12-44","Content":"发布iOSBook21","UserID":"tony"}]}
示例代码
import UIKitclass VIEwController: UIVIEwController {    var objects:NSMutableArray!=[]    overrIDe func vIEwDIDLoad() {        super.vIEwDIDLoad()        // Do any additional setup after loading the vIEw,typically from a nib.        let path=NSBundle.mainBundle().pathForResource("Notes",ofType: "Json")!        let JsonData=NSData(contentsOffile: path)!        //MutableContainers指定解析返回的是可变的数组或字典        let JsonObj:NSDictionary=(try? NSJsONSerialization.JsONObjectWithData(JsonData,options: NSJsONReadingOptions.MutableContainers)) as! NSDictionary        self.objects=JsonObj.objectForKey("Record") as! NSMutableArray        NSLog("\(self.objects)")    }    overrIDe func dIDReceiveMemoryWarning() {        super.dIDReceiveMemoryWarning()        // dispose of any resources that can be recreated.    }}
运行结果

总结

以上是内存溢出为你收集整理的Swift学习笔记(2)网络数据交换格式(XML,JSON)解析 [iOS实战 入门与提高卷]全部内容,希望文章能够帮你解决Swift学习笔记(2)网络数据交换格式(XML,JSON)解析 [iOS实战 入门与提高卷]所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1076069.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存