http://blog.csdn.net/ryantang03/article/details/7868246 html
在IOS平臺上進行XML文檔的解析有不少種方法,在SDK裏面有自帶的解析方法,可是大多狀況下都傾向於用第三方的庫,緣由是解析效率更高、使用上更方便,關於IOS平臺各類解析XML庫的優缺點分析,能夠看下這篇文章:http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project app
這裏主要介紹一下由Google提供的一種在IOS平臺上進行XML解析的開源庫GDataXML,能夠到http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/下載源碼,下載下來後進入文件夾找到XMLSupport文件夾,將裏面的GDataXMLNode.h和GDataXMLNode.m文件拖拽到項目中新建的文件夾便可(我這裏是建的GDataXML文件夾),注意要選中複製文件到項目中而不是隻是引用,如圖: iphone
![](http://static.javashuo.com/static/loading.gif)
而後就是對工程進行一些配置,點擊工程根目錄而後點擊左邊的Target,進入Build Phases,而後點擊第三個Link binary with libraries,點擊加號搜索libxml2並將這個庫添加到工程,如圖: ide
![](http://static.javashuo.com/static/loading.gif)
接下來再進入Build Settings,在搜索框中搜索Head Search Path,而後雙擊並點擊+按鈕添加/usr/include/libxml2,如圖: ui
接下來再搜索框中搜索Other linker flags,一樣的方式添加-lxml2,如圖: google
到這裏,添加和配置的工做就完成了(是有點麻煩),接下來就看如何使用了: spa
首先在工程中新建一個xml文件,做爲咱們要解析的對象,新建方法是在工程中新建一個Empty的文件,命名爲users.xml,而後添加內容: .net
- <?xml version="1.0" encoding="utf-8"?>
- <Users>
- <User id="001">
- <name>Ryan</name>
- <age>24</age>
- </User>
- <User id="002">
- <name>Tang</name>
- <age>23</age>
- </User>
- </Users>
接下來就能夠開始解析了,在須要解析的文件中引入頭文件:#import"GDataXMLNode.h" code
我是新建的一個Empty工程,因此直接在AppDelegate.m中使用,代碼以下: xml
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[[UIWindowalloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
- // Override point for customization after application launch.
- self.window.backgroundColor = [UIColorwhiteColor];
- [self.windowmakeKeyAndVisible];
-
- //獲取工程目錄的xml文件
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"users" ofType:@"xml"];
- NSData *xmlData = [[NSData alloc] initWithContentsOfFile:filePath];
-
- //使用NSData對象初始化
- GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0error:nil];
-
- //獲取根節點(Users)
- GDataXMLElement *rootElement = [doc rootElement];
-
- //獲取根節點下的節點(User)
- NSArray *users = [rootElement elementsForName:@"User"];
-
- for (GDataXMLElement *user in users) {
- //User節點的id屬性
- NSString *userId = [[user attributeForName:@"id"] stringValue];
- NSLog(@"User id is:%@",userId);
-
- //獲取name節點的值
- GDataXMLElement *nameElement = [[user elementsForName:@"name"] objectAtIndex:0];
- NSString *name = [nameElement stringValue];
- NSLog(@"User name is:%@",name);
-
- //獲取age節點的值
- GDataXMLElement *ageElement = [[user elementsForName:@"age"] objectAtIndex:0];
- NSString *age = [ageElement stringValue];
- NSLog(@"User age is:%@",age);
- NSLog(@"-------------------");
- }
-
- returnYES;
- }
編譯執行在控制檯輸出結果以下: