我计划开发一个应用程序,以便根据用户输入从文件中检索部分 xml 数据。我的代码可以很好地检索 xml 文件的内容,但我想不出让解析器给我所有内部元素的最佳方法,例如(intake name="TMF1202")......用户将将入口名称作为输入,解析器将检索仅存在于该入口标签中的元素,这是我的解析器代码:
#import "Parser.h"
#import "TimeTableViewController.h"
@implementation Parser
@synthesize currentElementPointer, rootElement;
-(id)initParser
{
if(self = [super init]) {
tvc = (TimeTableViewController*)[[UIApplication sharedApplication]delegate];
}
return self;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if(self.rootElement == nil) {
self.rootElement = [[List alloc]init];
self.currentElementPointer = self.rootElement;
} else {
List *newList = [[List alloc]init];
newList.parent = self.currentElementPointer;
[self.currentElementPointer.subElements addObject:newList];
self.currentElementPointer = newList;
}
self.currentElementPointer.name = elementName;
self.currentElementPointer.attributes = attributeDict;
// theList.intake = [[attributeDict objectForKey:@"name"]stringValue];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if([self.currentElementPointer.text length] > 0) {
self.currentElementPointer.text = [self.currentElementPointer.text stringByAppendingString:string];
} else {
self.currentElementPointer.text = string;
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
self.currentElementPointer = self.currentElementPointer.parent;
}
@end
这是我的 XML 文件的结构: