我试图解析一个xml,它有一个根元素,其中2个子元素具有相同的名称。然而,他们一直在联合起来。我怎样才能解决这个问题?这是我到目前为止的代码
-
(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
element = elementName;
if([element isEqualToString:@"bustime-response"]){
self.item = [[NSMutableDictionary alloc]init];
self.direction =[[NSMutableString alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([element isEqualToString:@"dir"]){
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[self.direction appendString:string];
}
}
答案 0 :(得分:0)
试试这个对我有用:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
element = elementName;
if ([element isEqualToString:@"bustime-response"])
{
elementFound = YES;
if (self.item)
self.item = nil;
self.item = [[NSMutableDictionary alloc]init];
if (self.direction)
self.direction = nil;
self.direction =[[NSMutableString alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (elementFound)
{
if ([element isEqualToString:@"dir"]){
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[self.direction appendString:string];
}
//Add another if with the tag you want to retrieve the data from here
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([element isEqualToString:@"bustime-response"])
{
elementFound = NO;
// self.receivedDataArray - main array to store all of your dictionary
[self.receivedDataArray addObject: self.direction];
[self.receivedDataArray addObject: self.item];
self.direction = nil;
self.item = nil;
}
}
如您所见,您必须添加另一个BOOL变量elementFound和NSMutableArray receivedDataArray来存储所有数据。试一试,让我知道它对你有用。记住添加NSLogs进行调试很好,它有很多帮助。