这是我的 countries.xml 文件。
有什么问题请回答我我是iOS新手.....
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict/>
<countris>
<country>
<countryname>india<countryname>
</country>
</countris>
</plist>
这是我的viewDidLoad
:
NSString *filename = [[NSBundle mainBundle] pathForResource:@"countris" ofType:@"xml"];
NSData *data = [NSData dataWithContentsOfFile:filename];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
Myparser *myParser = [[Myparser alloc] init];
[parser setDelegate:myParser];
BOOL success = [parser parse];
if (success)
{
NSMutableArray *users = [myParser arraydata];
NSString *log= [NSString stringWithFormat:
@"This is an array of User objects:\n\n%@",
[users description]];
NSLog(log);
}
else
{
NSLog(@"Error parsing document!");
[[[UIAlertView alloc] initWithTitle:nil
message:@"Error parsing document!"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
我的 Myparser.m 文件,我在其中实现了我的 NSXMLParserDelegate 协议
#import "Myparser.h"
#import "MyParserData.h"
@implementation Myparser
@synthesize mydata,myparser,arraydata,flag,currentElementValue;
- (id) init {
if(self = [super init]) {
currentElementValue = [[NSMutableString alloc] initWithString:@""];
arraydata = [[NSMutableArray alloc] init];
flag = FALSE;
}
return self;
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"countris"]) {
return;
} else if ([elementName isEqualToString:@"country"]) {
self.mydata = [[MyParserData alloc] init];
} else {
self.currentElementValue = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (self.currentElementValue) {
[self.currentElementValue appendString:string];
}
}
- (void)parser:(NSXMLParser *)parserdidEndElement:(NSString *)elementNamenamespaceURI: (NSString *)namespaceURIqualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"counteis"]) {
return;
}
if ([elementName isEqualToString:@"country"]) {
[self.arraydata addObject:mydata];
self.mydata = nil;
} else {
[self.mydata setValue:self.currentElementValue forKey:elementName];
}
self.currentElementValue = nil;
}
@end