假设需要被解析的XML数据文件users.xml如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?
xml
version
=
"1.0"
encoding
"utf-8"
?>
<
Users
>
User
id
"101"
>
name
>航歌</
>
tel
>
mobile
>1234567</
>
home
>025-8100000</
>
</
>
User
>
"102"
>
>hangge</
>
>
>8989889</
>
>025-8122222</
>
>
>
>
|
User: uid:
101
,uname:航歌,mobile:
1234567
025
-
8100000
102
8989889
8122222
|
一,使用GdataxML(这个是google出品的)
1,在build phases -> Link Binary With Libraries中,点击“+”添加“libxml2.2.tbd”
2,在build setting -> Header Search Paths里添加 ${SDK_DIR}/usr/include/libxml2
#
import
"GdataxMLNode.h"
|
6,开始解析(ViewController.swift)
import
UIKit
class
ViewController
:
UIViewController
{
override
func
viewDidLoad() {
super
.viewDidLoad()
let
label:
UILabel
=
(frame:
CGRectMake
(100,100,300,100));
label.text =
"输出结果在控制台"
self
.view.addSubview(label)
testXML()
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
testXML() {
path =
NSBundle
.mainBundle().pathForResource(
"users"
"xml"
)
xmlData =
NSData
(contentsOfFile:path!)
//可以转换为字符串输出查看
//print(NSString(data:xmlData,encoding:NSUTF8StringEncoding))
//使用NSData对象初始化文档对象
//这里的语法已经把OC的初始化函数直接转换过来了
//获取Users节点下的所有User节点,显式转换为element类型编译器就不会警告了
//var users = doc.rootElement().elementsForName("User") as GdataxMLElement[]
//通过XPath方式获取Users节点下的所有User节点,在路径复杂时特别方便
for
user
in
users {
//User节点的id属性
uid = user.attributeForName(
"id"
).stringValue()
//获取name节点元素
//获取元素的值
uname = nameElement.stringValue()
//获取tel子节点
telElement = user.elementsForName(
"tel"
GdataxMLElement
//获取tel节点下mobile和home节点
mobile = (telElement.elementsForName(
"mobile"
)[0]
).stringValue()
home = (telElement.elementsForName(
"home"
)[0]
).stringValue()
//输出调试信息
print
(
"User: uid:\(uid),uname:\(uname),mobile:\(mobile),home:\(home)"
)
}
}
}
|
二,使用DDXML
1,使用方法 (1)前面配置同GdataxML 的1,2,3步一样