GDataXMLNode應用

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] );


//取出document對象    
    GDataXMLDocument* document = [[GDataXMLDocument alloc] initWithXMLString:myResponseStr options:2 error:nil];
    //取出xml的根節點
    GDataXMLElement* rootElement = [document rootElement];
    NSLog(@"--------root element:--------\n%@",rootElement);
    //取出根節點的所有孩子節點
    NSArray* children = [rootElement children];
    NSLog(@"--------root's children:--------\n%@", children);
    //取出某一個具體節點(body節點)
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"item"]objectAtIndex:1];
    NSLog(@"--------body:--------\n%@", bodyElement);
    //某個具體節點的文本內容
    NSString* content = [bodyElement stringValue];
    NSLog(@"--------body's content:--------\n%@", content);


//實例


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

[html] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2. #import "GDataXMLNode.h"  
  3.   
  4. @interface BaseParser : NSObject  
  5. {  
  6.     NSString                                      *xmlContent;        //字符串形式的xml內容  
  7.     NSMutableDictionary            *parsedContent; //對應的字典  
  8. }  
  9.   
  10. @property(nonatomic,retain)NSString *xmlContent;  
  11.   
  12. - (id)initWithXmlString:(NSString *)xmlString;  
  13. - (NSDictionary *)getCurrentList;  
  14. - (id)initWithUserDicionary:(NSDictionary*)dicionary;  
  15. - (id)getCurrentData;  
  16. @end  

BaseParser.m

[html] view plaincopy
  1. #import "BaseParser.h"  
  2. @implementation Baseparser  
  3. @synthesize xmlContent;  
  4. -(id)init  
  5. {  
  6.     self = [super init];  
  7.     if (self) {  
  8.         parsedContent = [[NSMutableDictionary alloc]init];  
  9.         xmlContent    = [[NSString alloc]init];  
  10.     }  
  11.     return self;  
  12. }  
  13. -(void)dealloc  
  14. {  
  15.     [parsedContent release];  
  16.     [xmlContent release];  
  17.     [super dealloc];  
  18.       
  19. }  
  20. - (id)initWithXmlString:(NSString *)xmlString  
  21. {  
  22.     return nil;  
  23. }  
  24. - (id)initWithUserDicionary:(NSDictionary *)dicionary  
  25. {  
  26.     return nil;  
  27. }  
  28.   
  29. - (NSDictionary *)getCurrentList  
  30. {  
  31.     return [NSDictionary dictionaryWithDictionary:parsedContent];   
  32. }  
  33. - (id)getCurrentData  
  34. {  
  35.     return [NSString stringWithString:xmlContent];  
  36. }  

LoginParser.h

[html] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2. #import "BaseParser.h"  
  3.   
  4. @interface LoginParser : BaseParser  
  5.   
  6. @end  

LoginParser.m

[html] view plaincopy
  1. #import "LoginParser.h"  
  2.   
  3. @implementation LoginParser  
  4. - (void)dealloc  
  5. {  
  6.     [super dealloc];  
  7. }  
  8. - (id)initWithXmlString:(NSString *)xmlString  
  9. {  
  10.     self = [super init];  
  11.     if (self) {  
  12.         NSError *error;  
  13.         GDataXMLDocument *dataDocument = [[GDataXMLDocument alloc]initWithXMLString:xmlString options:0 error:&error ];  
  14.         GDataXMLElement *root = [dataDocument rootElement];  
  15.         NSArray *array = [NSArray arrayWithObjects:@"code",@"desc",@"sessionId",@"user_id",@"name", nil];  
  16.         for (int index = 0; index<[array count]; index++) {  
  17.             GDataXMLElement *element = [[root elementsForName:[array objectAtIndex:index]]lastObject];  
  18.             NSString *aValue = (NSString*)[element stringValue];  
  19.             if (aValue) {  
  20.                 [parsedContent  setObject:aValue forKey:[array objectAtIndex:index]];  
  21.             }  
  22.         }  
  23.         [dataDocument release];  
  24.           
  25.     }  
  26.     return self;  
  27. }  
  28. - (id)initWithUserDicionary:(NSDictionary *)dicionary  
  29. {  
  30.     self = [self init];  
  31.     if (self) {  
  32.         [dicionary retain];  
  33.         GDataXMLElement *rootElement = [GDataXMLElement elementWithName:@"root"];  
  34.         NSArray *elementArray = [NSArray arrayWithObjects:@"name",@"type",@"password", nil];  
  35.         for (int index = 0; index<[elementArray count]; index++) {  
  36.             GDataXMLElement *element = [GDataXMLElement elementWithName:[elementArray objectAtIndex:index] stringValue:[dicionary objectForKey:[elementArray objectAtIndex:index]]];  
  37.             [rootElement addChild:element];  
  38.         }  
  39.         [dicionary release];  
  40.         GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc]initWithRootElement:rootElement];  
  41.         NSString *xmlString = [[NSString alloc]initWithData:xmlDocument.XMLData encoding:NSUTF8StringEncoding];  
  42.         xmlContent = @"";  
  43.         xmlContent = [xmlContent stringByAppendingString:xmlString];  
  44.         [xmlString release];  
  45.         [xmlDocument release];  
  46.           
  47.     }  
  48.       
  49.     return self;  
  50. }  


DataParser.h

[html] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface DataParser : NSObject  
  4.   
  5.   
  6. + (id)CreateParserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType;     // 根據不同的類型用字典組裝成xml  
  7. + (id)CreateDeparserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType;//將xml解析成字典  
  8. @end  


DataParser.m

[html] view plaincopy
  1. #import "LoginParser.h"  
  2. @implementation DataParser  
  3. //這倆個簡單的工廠來組裝和解析xml   
  4. + (id)CreateParserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType  
  5. {  
  6.     switch (aType) {  
  7.         case LOGINSERVICETYPE :  
  8.         {  
  9.             LoginParser *parser  = [[BCLogin alloc]initWithXmlString:xmlString];  
  10.             NSDictionary *dictionary = [urlList getCurrentList];  
  11.             [ parser release];  
  12.             return dictionary ;  
  13.         }  
  14.             break;  
  15. }  
[html] view plaincopy
  1. + (id)CreateDeparserObjectWithData:(id)xmlString andTypeIs:(NSInteger)aType  
  2. {  
  3.       
  4.     switch (aType) {  
  5.         case LOGINSERVICETYPE :  
  6.         {  
  7.             LoginParser *parser = [[BCLogin alloc]initWithUserDicionary:xmlString];  
  8.             NSData  *data    = [urlList getCurrentData];  
  9.             [parser release];  
  10.             return data ;  
  11.         }  
  12.             break;  
  13. }  

4:使用

新建一個文件LoginViewController,在程序束中加入 LoginReturn.xml,

LoginViewController.m

[html] view plaincopy
  1. #define    LOGINSERVICETYPE  100  
  2. #import "LoginViewController.h"  
  3.   
  4. @implementation LoginViewController  
  5.   
  6. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  7. {  
  8.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  9.     if (self) {  
  10.         // Custom initialization  
  11.     }  
  12.     return self;  
  13. }  
  14.   
  15. - (void)didReceiveMemoryWarning  
  16. {  
  17.     // Releases the view if it doesn't have a superview.  
  18.     [super didReceiveMemoryWarning];  
  19.       
  20.     // Release any cached data, images, etc that aren't in use.  
  21. }  
  22.   
  23. #pragma mark - View lifecycle  
  24.   
  25. - (void)viewDidLoad  
  26. {  
  27.     [super viewDidLoad];  
  28.     // Do any additional setup after loading the view from its nib.  
  29.  <span style="color:#FF0000;">  //使用解析的工廠,組裝xml就不寫了  
  30.     NSString *string =  NSError *error;  
  31.     NSString *xmlString = [NSString stringWithContentsOfFile:[[[NSBundle mainBundle]bundlePath]stringByAppendingPathComponent:@"LoginReturn.xml"]   
  32.      encoding:NSUTF8StringEncoding error:&error];  
  33.      NSMutableDictionary *dic =    [NSMutableDictionary dictionaryWithDictionary:  
  34.                                                                    [BCBaseParser CreateParserObjectWithData:xmlString andTypeIs:self.parserType]]  
  35.    //這裏獲得的dic就是包含了sessionId,userId,等鍵的字典</span>  
  36.  }  
  37.   
  38. - (void)viewDidUnload  
  39. {  
  40.     [super viewDidUnload];  
  41.     // Release any retained subviews of the main view.  
  42.     // e.g. self.myOutlet = nil;  
  43. }  
  44.   
  45. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  46. {  
  47.     // Return YES for supported orientations  
  48.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
  49. }  
  50.   
  51. @end  

 不好把我在項目中的代碼貼出來,我是在post不同的xml中用到這個方式

轉載請註明出處


總結:

        代碼的重用非常重要,在開發過程中儘量遵守一般的開發原則,比如OCP,這篇文中較好的體現了這一原則,同時GDataXmlNode避免了官方的類回調的使用,十分方便,推薦使用。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章