標籤:http color io os 使用 ar for 檔案 2014
iOS GData 解析XML 總結
在iOS平台上進行XML解析的方法有很多,在SDK中又內建的解析方法。但是我們更傾向於使用第三方庫,原因是解析效率高,使用更加方便。下面介紹Google下的開源庫GData解析XML。
可以到http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/下載源碼,下載下來後進入檔案夾找到XMLSupport檔案夾,將裡面的GDataXMLNode.h和GDataXMLNode.m檔案拖拽到項目中建立的檔案夾即可(我這裡是建的GDataXML檔案夾),注意要選中複製檔案到項目中而不是只是引用,
工程進行一些配置,點擊工程根目錄然後點擊左邊的Target,進入Build Phases,然後點擊第三個Link binary with libraries,點擊加號搜尋libxml2並將這個庫添加到工程,
接下來再進入Build Settings,在搜尋方塊中搜尋Head Search Path,然後雙擊並點擊+按鈕添加/usr/include/libxml2,
接下來再搜尋方塊中搜尋Other linker flags,同樣的方式添加-lxml2,
作就完成了(是有點麻煩),接下來就看如何使用了:
首先在工程中建立一個xml檔案,作為我們要解析的對象,建立方法是在工程中建立一個Empty的檔案,命名為users.xml,然後新增內容:
- <?xml version="1.0" encoding="utf-8"?>
- <Users>
- <User id="001">
- <name>寒竹子</name>
- <age>24</age>
- </User>
- <User id="002">
- <name>hzz</name>
- <age>23</age>
- </User>
- </Users>
接下來就可以開始解析了,在需要解析的檔案中引入標頭檔:#import"GDataXMLNode.h"
我是建立的一個Empty工程,所以直接在AppDelegate.m中使用,代碼如下:
#import "XRAppDelegate.h"
#import "GDataXMLNode.h"
@implementation XRAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// 擷取工程目錄下的xml檔案
NSString * filePath = [[NSBundle mainBundle] pathForResource:@"users" ofType:@"xml"];
// 將xml檔案的內容轉為NSdata類型
NSData * data = [NSData dataWithContentsOfFile:filePath];
// 初始化GData對象 建立文檔樹
GDataXMLDocument * doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
// 擷取根節點 (Users)
GDataXMLElement * rootElement = [doc rootElement];
NSArray * users = [rootElement elementsForName:@"User"];
// 遍曆節點
for (GDataXMLElement * user in users) {
// 取得user節點的id屬性
NSString * userId = [[user attributeForName:@"id"] stringValue];
// 擷取name節點的值
GDataXMLElement * nameElement = [[user elementsForName:@"name"] objectAtIndex:0];
NSString * name = [nameElement stringValue];
// 擷取age節點的值
GDataXMLElement * ageElement = [[user elementsForName:@"age"] objectAtIndex:0];
NSString * age = [ageElement stringValue];
NSLog(@"userId: %@", userId);
NSLog(@"name: %@", name);
NSLog(@"age: %@", age);
}
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
END
iOS-GData解析XML