1,安装:将GdataxMLNode文件加入至工程中->向Frameworks文件中添加libxml2.dylib库->在Croups & Files 侧边栏中双击工程图标,找到 build 修改两个属性:Search Paths中 找到Header Search Paths 将其对应的值修改为:/usr/include/libxml2,在Linking中找到 Other Linker Flags 对应的值改为:-lxml2。——-安装完成。
2,
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文件--
import
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
[html] view plaincopy
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
[html] view plaincopy
import
import “BaseParser.h”
@interface LoginParser : BaseParser
@end
LoginParser.m
[html] view plaincopy
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
[html] view plaincopy
import
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;
}
[html] view plaincopy
+ (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
[html] view plaincopy
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.
//使用解析的工厂,组装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,等键的字典
}(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避免了官方的类回调的使用,十分方便,推荐使用。