XML文件解析

- (void)loadView {

UITextView *back = [[UITextView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
back.textColor = [UIColor redColor];
back.backgroundColor = [UIColor whiteColor];
self.view = back;

}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];

NSString *headPath = [[NSBundle mainBundle] resourcePath];
NSString *filePath = [[NSString alloc] initWithFormat:@"%@/enen2.xml",headPath];
NSString *content = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:content options:1 error:nil];
GDataXMLElement *rootElement = [document rootElement];

NSDictionary *dic;
dic = [self getElementFromXMLDATA:rootElement];
NSLog(@"%@",dic);
//
// [(UITextView *)self.view setText:[str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

}


-(id)getElementFromXMLDATA:(GDataXMLElement *)_theElement
{
id result = nil;
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc]init] autorelease];
if ([[_theElement children] count] == 0) {
if ([[_theElement stringValue] length] != 0) {
result = [_theElement stringValue];
}
else {
for (GDataXMLNode *keyNode in [_theElement attributes]) {
[dictionary setObject:[[_theElement attributeForName:[keyNode name]] stringValue] forKey:[keyNode name]];
}
result = [NSDictionary dictionaryWithObject:dictionary forKey:[_theElement name]];
}
}
else {
id _result = nil;
NSMutableArray *array = [[NSMutableArray alloc]init];
for (GDataXMLElement *childElement in [_theElement children]) {
_result = [self getElementFromXMLDATA:childElement];
if ([_result class] != NSClassFromString(@"__NSCFDictionary")) {
}
else {
[array addObject:[self getElementFromXMLDATA:childElement]];
_result = array;
}
}
[dictionary setObject:_result forKey:[_theElement name]];
result = dictionary;
[array release];
}
return result;
}

 

 

+++++++++++++++++++++++++++++++++++++++++++++++++++++

enen2.xml文件中的内容:

<?xml version='1.0' encoding='UTF-8'?><brands>

<brand name="福田汽车">

<series name="蒙派克"/>

<series>"MP-X蒙派克"</series>

<series>"风景"</series>

<series>"迷迪"</series>

<series>"传奇"</series>

<series name= "宝马良驹"/>

<series age="16" name="sdf"/>

</brand>

</brands>

posted @ 2011-11-14 20:07  松花江以南  阅读(572)  评论(0编辑  收藏  举报