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

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

Swift学习笔记(2)网络数据交换格式(XML,JSON)解析

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

  • 用NSXML来解析XML文档
  • 用TBXML来解析XML文档
  • 用NSJSONSerialization来解析JSON文档

目录


用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 Foundation

class 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, namespaceURI: 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 parse
2016-05-17 12:03:42.852 XMLTest[61377:445073] end parse
2016-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 Foundation

class 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","UserID":"tony"},
{"ID":"3","CDate":"2014-12-25","Content":"发布iOSBook2","UserID":"tony"},
{"ID":"4","CDate":"2014-12-26","Content":"发布iOSBook3","UserID":"tony"},
{"ID":"5","CDate":"2014-12-27","Content":"发布iOSBook4","UserID":"tony"},
{"ID":"6","CDate":"2014-12-28","Content":"发布iOSBook5","UserID":"tony"},
{"ID":"7","CDate":"2014-12-29","Content":"发布iOSBook6","UserID":"tony"},
{"ID":"8","CDate":"2014-12-30","Content":"发布iOSBook7","UserID":"tony"},
{"ID":"9","CDate":"2014-12-31","Content":"发布iOSBook8","UserID":"tony"},
{"ID":"10","CDate":"2014-12-32","Content":"发布iOSBook9","UserID":"tony"},
{"ID":"11","CDate":"2014-12-33","Content":"发布iOSBook10","UserID":"tony"},
{"ID":"12","CDate":"2014-12-34","Content":"发布iOSBook11","UserID":"tony"},
{"ID":"13","CDate":"2014-12-35","Content":"发布iOSBook12","UserID":"tony"},
{"ID":"14","CDate":"2014-12-36","Content":"发布iOSBook13","UserID":"tony"},
{"ID":"15","CDate":"2014-12-37","Content":"发布iOSBook14","UserID":"tony"},
{"ID":"16","CDate":"2014-12-38","Content":"发布iOSBook15","UserID":"tony"},
{"ID":"17","CDate":"2014-12-39","Content":"发布iOSBook16","UserID":"tony"},
{"ID":"18","CDate":"2014-12-40","Content":"发布iOSBook17","UserID":"tony"},
{"ID":"19","CDate":"2014-12-41","Content":"发布iOSBook18","UserID":"tony"},
{"ID":"20","CDate":"2014-12-42","Content":"发布iOSBook19","UserID":"tony"},
{"ID":"21","CDate":"2014-12-43","Content":"发布iOSBook20","UserID":"tony"},
{"ID":"22","CDate":"2014-12-44","Content":"发布iOSBook21","UserID":"tony"}]}

示例代码

import UIKit

class 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.
    }


}

运行结果

目录
相关文章
|
1月前
|
XML JavaScript 前端开发
xml文件使用及解析
xml文件使用及解析
|
1天前
|
XML 存储 JSON
c#XML、JSON的序列化和反序列化,看完你就懂了
c#XML、JSON的序列化和反序列化,看完你就懂了
6 0
|
10天前
|
XML JSON 前端开发
【Web 前端】XML和JSON的区别?
【4月更文挑战第22天】【Web 前端】XML和JSON的区别?
【Web 前端】XML和JSON的区别?
|
13天前
|
XML 存储 数据格式
探索 DTD 在 XML 中的作用及解析:深入理解文档类型定义
DTD(文档类型定义)用于定义XML文档的结构和合法元素、属性。它允许不同团体就数据交换标准达成一致,并用于验证XML数据的有效性。DTD可通过内部声明(在XML文档内)或外部声明(在单独文件中)来定义。内部声明示例显示了如何定义`note`元素及其子元素的结构,而外部声明则引用外部DTD文件。元素、属性、实体和PCDATA/CDATA是XML构建模块。DTD中,元素通过ELEMENT声明定义,属性通过ATTLIST声明定义,实体声明提供特殊字符或外部资源的快捷方式。
15 0
|
14天前
|
XML JSON 中间件
中间件数据格式JSON与XML之间的转换
中间件数据格式JSON与XML之间的转换
26 3
|
17天前
|
XML Java 数据库连接
Javaweb之Mybatis的XML配置文件的详细解析
Javaweb之Mybatis的XML配置文件的详细解析
15 0
|
20天前
|
XML C# 数据格式
C# 解析XML文件
C# 解析XML文件
25 1
|
1月前
|
XML JSON JavaScript
Java中XML和JSON的比较与应用指南
本文对比了Java中XML和JSON的使用,XML以自我描述性和可扩展性著称,适合结构复杂、需验证的场景,但语法冗长。JSON结构简洁,适用于轻量级数据交换,但不支持命名空间。在Java中,处理XML可使用DOM、SAX解析器或XPath,而JSON可借助GSON、Jackson库。根据需求选择合适格式,注意安全、性能和可读性。
28 0
|
1月前
|
移动开发 小程序 API
uniapp通过蓝牙传输数据 (ios)
uniapp通过蓝牙传输数据 (ios)
51 1
|
1月前
|
XML JSON 安全
xml与json的区别
xml与json的区别
10 0

推荐镜像

更多