1,安裝:將GDataXMLNode文件加入至工程中->向Frameworks文件中添加libxml2.dylib庫->在Croups & Files 側邊欄中雙擊工程圖標,找到 build 修改兩個屬性:Search Paths中 找到Header Search Paths 將其對應的值修改爲:/usr/include/libxml2,在Linking中找到 Other Linker Flags 對應的值改爲:-lxml2。-------安裝完成。
2,
//獲取工程目錄的xml文件
NSString *filePath = [[NSBundlemainBundle] pathForResource:@"users"ofType:@"xml"];
NSData *xmlData = [[NSDataalloc] initWithContentsOfFile:filePath];
//使用NSData對象初始化
NSError *error=nil;
GDataXMLDocument *doc = [[GDataXMLDocumentalloc] initWithData:xmlData options:0 error:&error];
//獲取根節點(Users)
GDataXMLElement *rootElement = [doc rootElement];
//獲取根節點下的節點(User)
NSArray *users = [rootElement elementsForName:@"User"];
for (GDataXMLElement *userin users) {
//User節點的id屬性
NSString *userId = [[user attributeForName:@"id"] stringValue];
NSLog(@"User id is:%@",userId);
//獲取name節點的值
GDataXMLElement *nameElement = [[userelementsForName:@"name"] objectAtIndex:0];
NSString *name = [nameElement stringValue];
NSLog(@"User name is:%@",name);
//獲取age節點的值
GDataXMLElement *ageElement = [[userelementsForName:@"age"] objectAtIndex:0];
NSString *age = [ageElement stringValue];
NSLog(@"User age is:%@",age);
NSLog(@"-------------------");
}
附:xml文件--
<?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>
----------------------------------------------------
GDataXml 相同標籤的多個屬性
GDataXml 相同標籤的多個屬性,好多文檔都沒有介紹獲取屬性的方法GDataXMLDocument
*doc=[[GDataXMLDocument alloc]initWithXMLString:resp*****eBody opti*****:2 error:nil];
if (doc!=nil) {
GDataXMLElement *root=[doc rootElement ];
NSLog(@"--------root's children:--------\n%@", root);
//取出根節點的所有孩子節點
//取出某一個具體節點(body節點)
[returnInfo setObject:[[[root elementsForName:@"db:uid"] objectAtIndex:0] stringValue] forKey:@"snsUserUid"];
[returnInfo setObject:[[[root elementsForName:@"title"]objectAtIndex:0]stringValue] forKey:@"snsNickName"];
[returnInfo setObject:[[[root elementsForName:@"db:location"]objectAtIndex:0]stringValue] forKey:@"snsProvince"];
[returnInfo setObject:[[[[root elementsForName:@"link"] objectAtIndex:2]attributeForName:@"href"]
stringValue] forKey:@"snsProfileImageUrl"];
[returnInfo setObject:@"4" forKey:@"snsLandEntrance"];
NSLog(@"%@",[[[root elementsForName:@"link"] objectAtIndex:2]attributes]);
NSLog(@"%@",[[[root elementsForName:@"db:location"]objectAtIndex:0]stringValue]);
}
NSLog(@"returnInforeturnInforeturnInforeturnInforeturnInfo%@",returnInfo);
附上xml源文件:
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:db="http://www.douban.com/xmlns/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:opensearch="http://a9.com/-/spec/opensearchrss/1.0/">
<id>http://api.douban.com/people/63522291</id>
<title>wangjianlewo</title>
<link href="http://api.douban.com/people/63522291" rel="self"/>
<link href="http://www.douban.com/people/63522291/" rel="alternate"/>
<link href="http://img3.douban.com/icon/user_normal.jpg" rel="icon"/>
<content></content>
<db:attribute name="n_mails">0</db:attribute>
<db:attribute name="n_notificati*****">0</db:attribute>
<db:location id="beijing">北京</db:location>
<db:signature></db:signature>
<db:uid>63522291</db:uid>
<uri>http://api.douban.com/people/63522291</uri>
</entry>
------------------------
下面是得到屬性裏的值。Google爲我們做了很多的事情,不得不感慨GDataXMLNode給我們帶來了如此多的便利
直接代碼:
NSArray *getItems = [document nodesForXPath:@"//item" error:&error];
這裏給出了一個老外寫的代碼:
/////////////////////// 截取屬性應用舉例
//NSInteger type=[[(GDataXMLNode *)[[urls objectAtIndex:i] attributeForName:@"type"] stringValue] intValue];
//NSInteger bit_stream=[[(GDataXMLNode *)[[urls objectAtIndex:i] attributeForName:@"bit_stream"] stringValue] intValue];
///////////////////////////////////////////
//// 調試信息 看是否獲取屬性成功 //////
//////////////////////////////////////////
NSLog(@"%@",[(GDataXMLNode *)[[getItems objectAtIndex:0]attributeForName:@"name"]stringValue] );
//實例
xml的解析在ios網絡開發的時候非常常見,不同的xml的樹形的結構各不相同,這篇文中介紹根據不同的xml的結構解析出xml,保存到字典中,如果解析的數據將會多次用到,建議建立數據實體,不然在多個場景中都必須知道字典中的鍵值,用起來非常不方便。
我最近開發的項目中用到xml解析,我用到一個工廠模式來建立一個解析的方式。
1: 我在這個過程中用到6個文件,BaseParser.h,BaseParser.m,DataParser.h和DataParser.m ,LoginParser.h,LoginParser.m,其中BaseParser用於定義和實現基類的方法,LoginParser繼承於BaserParser,實現了父類中申明的解析xml文件和組裝xml文件的方法。DataParser中根據不同的xml類型來實例化解析類,這裏就是LoginParser(也就是說,還可以實例化任意多個BaseParser的子類).
2,GDataxmlNode 的使用在LoginParser中很能得以體現總的思路就是 字典,字符串,GDataxmlDocumet 這個類型的實例之間相互轉化,以完成xml的組裝和解析。
BaseParser.h
- #import <Foundation/Foundation.h>
- #import "GDataXMLNode.h"
- @interface BaseParser : NSObject
- {
- NSString *xmlContent; //字符串形式的xml內容
- NSMutableDictionary *parsedContent; //對應的字典
- }
- @property(nonatomic,retain)NSString *xmlContent;
- - (id)initWithXmlString:(NSString *)xmlString;
- - (NSDictionary *)getCurrentList;
- - (id)initWithUserDicionary:(NSDictionary*)dicionary;
- - (id)getCurrentData;
- @end
BaseParser.m
- #import "BaseParser.h"
- @implementation Baseparser
- @synthesize xmlContent;
- -(id)init
- {
- self = [super init];
- if (self) {
- parsedContent = [[NSMutableDictionary alloc]init];
- xmlContent = [[NSString alloc]init];
- }
- return self;
- }
- -(void)dealloc
- {
- [parsedContent release];
- [xmlContent release];
- [super dealloc];
- }
- - (id)initWithXmlString:(NSString *)xmlString
- {
- return nil;
- }
- - (id)initWithUserDicionary:(NSDictionary *)dicionary
- {
- return nil;
- }
- - (NSDictionary *)getCurrentList
- {
- return [NSDictionary dictionaryWithDictionary:parsedContent];
- }
- - (id)getCurrentData
- {
- return [NSString stringWithString:xmlContent];
- }
LoginParser.h
- #import <Foundation/Foundation.h>
- #import "BaseParser.h"
- @interface LoginParser : BaseParser
- @end
LoginParser.m
- #import "LoginParser.h"
- @implementation LoginParser
- - (void)dealloc
- {
- [super dealloc];
- }
- - (id)initWithXmlString:(NSString *)xmlString
- {
- self = [super init];
- if (self) {
- NSError *error;
- GDataXMLDocument *dataDocument = [[GDataXMLDocument alloc]initWithXMLString:xmlString options:0 error:&error ];
- GDataXMLElement *root = [dataDocument rootElement];
- NSArray *array = [NSArray arrayWithObjects:@"code",@"desc",@"sessionId",@"user_id",@"name", nil];
- for (int index = 0; index<[array count]; index++) {
- GDataXMLElement *element = [[root elementsForName:[array objectAtIndex:index]]lastObject];
- NSString *aValue = (NSString*)[element stringValue];
- if (aValue) {
- [parsedContent setObject:aValue forKey:[array objectAtIndex:index]];
- }
- }
- [dataDocument release];
- }
- return self;
- }
- - (id)initWithUserDicionary:(NSDictionary *)dicionary
- {
- self = [self init];
- if (self) {
- [dicionary retain];
- GDataXMLElement *rootElement = [GDataXMLElement elementWithName:@"root"];
- NSArray *elementArray = [NSArray arrayWithObjects:@"name",@"type",@"password", nil];
- for (int index = 0; index<[elementArray count]; index++) {
- GDataXMLElement *element = [GDataXMLElement elementWithName:[elementArray objectAtIndex:index] stringValue:[dicionary objectForKey:[elementArray objectAtIndex:index]]];
- [rootElement addChild:element];
- }
- [dicionary release];
- GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc]initWithRootElement:rootElement];
- NSString *xmlString = [[NSString alloc]initWithData:xmlDocument.XMLData encoding:NSUTF8StringEncoding];
- xmlContent = @"";
- xmlContent = [xmlContent stringByAppendingString:xmlString];
- [xmlString release];
- [xmlDocument release];
- }
- return self;
- }
DataParser.h
- #import <Foundation/Foundation.h>
- @interface DataParser : NSObject
- + (id)CreateParserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType; // 根據不同的類型用字典組裝成xml
- + (id)CreateDeparserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType;//將xml解析成字典
- @end
DataParser.m
- #import "LoginParser.h"
- @implementation DataParser
- //這倆個簡單的工廠來組裝和解析xml
- + (id)CreateParserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType
- {
- switch (aType) {
- case LOGINSERVICETYPE :
- {
- LoginParser *parser = [[BCLogin alloc]initWithXmlString:xmlString];
- NSDictionary *dictionary = [urlList getCurrentList];
- [ parser release];
- return dictionary ;
- }
- break;
- }
- + (id)CreateDeparserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType
- {
- switch (aType) {
- case LOGINSERVICETYPE :
- {
- LoginParser *parser = [[BCLogin alloc]initWithUserDicionary:xmlString];
- NSData *data = [urlList getCurrentData];
- [parser release];
- return data ;
- }
- break;
- }
4:使用
新建一個文件LoginViewController,在程序束中加入 LoginReturn.xml,
LoginViewController.m
- #define LOGINSERVICETYPE 100
- #import "LoginViewController.h"
- @implementation LoginViewController
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- - (void)didReceiveMemoryWarning
- {
- // Releases the view if it doesn't have a superview.
- [super didReceiveMemoryWarning];
- // Release any cached data, images, etc that aren't in use.
- }
- #pragma mark - View lifecycle
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view from its nib.
- <span style="color:#FF0000;"> //使用解析的工廠,組裝xml就不寫了
- NSString *string = NSError *error;
- NSString *xmlString = [NSString stringWithContentsOfFile:[[[NSBundle mainBundle]bundlePath]stringByAppendingPathComponent:@"LoginReturn.xml"]
- encoding:NSUTF8StringEncoding error:&error];
- NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:
- [BCBaseParser CreateParserObjectWithData:xmlString andTypeIs:self.parserType]]
- //這裏獲得的dic就是包含了sessionId,userId,等鍵的字典</span>
- }
- - (void)viewDidUnload
- {
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- // e.g. self.myOutlet = nil;
- }
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- // Return YES for supported orientations
- return (interfaceOrientation == UIInterfaceOrientationPortrait);
- }
- @end
不好把我在項目中的代碼貼出來,我是在post不同的xml中用到這個方式
轉載請註明出處
總結:
代碼的重用非常重要,在開發過程中儘量遵守一般的開發原則,比如OCP,這篇文中較好的體現了這一原則,同時GDataXmlNode避免了官方的類回調的使用,十分方便,推薦使用。