获取文件并开始解析
NSError *error;
NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"xml"];
NSString* contents = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:&error];
self.xmlData = [[NSData alloc] init];
self.xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];
self.xmlParser = [[NSXMLParser alloc] initWithData:self.xmlData];
[self.xmlParser setDelegate: self];
[self.xmlParser setShouldResolveExternalEntities: YES];
[self.xmlParser parse];
然后用于解析
BOOL isValid_child1 = NO;
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"child1"]) {
isValid_child1 = YES;
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (isValid_child1) {
valueInChild1 = string; // string is txt1
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"child1"]) {
isValid_child1 = NO;
[array addObject:valueInChild1]; // to add value for child1 to an array
}
我知道这很脏;) 但它有效,你可以更灵活地做到这一点。