我正在研究一个nsxml解析器,我有一些问题。我正在使用nsxml解析器来解析日期。我想获得仅2天的信息。不是全部4个来自google weather api。我该怎么办?
NSMutableArray *array=[NSMutableArray arrayWithObjects:startDate,endDate,Nil];
for (NSDate *date in array)
{
if([date isEqualToDate:dd])
{
NSManagedObject *allnew = Nil;
NSManagedObjectContext *allone=[self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Weather" inManagedObjectContext:allone];
NSLog(@" The NEW ENTITY IS ALLOCATED AS entity is %@",entity);
WeatherXMLParser *delegate = [[WeatherXMLParser alloc] initWithCity:city state:state country:country];
NSXMLParser *locationParser = [[NSXMLParser alloc] initWithContentsOfURL:delegate.url];
[locationParser setDelegate:delegate];
[locationParser setShouldResolveExternalEntities:YES];
[locationParser parse];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
predicate = [NSPredicate predicateWithFormat:
@"city == %@ and state == %@ and country == %@ and date==%@ and date==%@", city, state, country,startDate,endDate];
[request setPredicate:predicate];
NSError *err;
NSUInteger count = [allone countForFetchRequest:request error:&err];
NSLog(@" minimum salary is %@",predicate);
// If a predicate was passed, pass it to the query
if(predicate !=NULL){
[self deleteobject];
}
Weather *weather = (Weather *)[NSEntityDescription insertNewObjectForEntityForName:@"Weather"
inManagedObjectContext:self.managedObjectContext];
weather.date = [fields objectForKey:@"date"];
weather.high =[fields objectForKey:@"high"];
weather.low = [fields objectForKey:@"low"];
weather.city =[fields objectForKey:@"city"];
weather.state =[fields objectForKey:@"state"];
weather.country =[fields objectForKey:@"country"];
NSString*icon=[fields objectForKey:@"icon"];
NSString *all=[icon lastPathComponent];
weather.condition = all;
[self saveContext];
}
答案 0 :(得分:0)
我不熟悉你的XML文件是如何组织的但我认为问题是有4个以上的节点具有相同的名称,你只想要2.当我遇到类似的情况时,我设置了一个标志对于我自己想要的最后一个节点之后,我从来没有读过任何其他节点。
在您的特定情况下,创建一个计数器,显示您已阅读的天数,解析时检查以确保节点名称为“date”(或者您现在正在执行的任何操作以触发读取信息)并且您的计数器小于2.请确保每次调用天气更新时都重置计数器。
编辑一些示例代码:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"Day"] && daysRead < 2) {
if ([[attributeDict objectForKey:@"high"] integerValue] > 0) {
//Store store this value
}
if ([[attributeDict objectForKey:@"low"] integerValue] > 0) {
//Store this value
}
}
}
这是我的解析器的一部分,我有点为你重写它。您感兴趣的部分是变量'daysRead'。我建议使用这样的东西来跟踪你已经阅读和存储的天数。如果您有两个以上,则根本不解析剩余的天数。在完成每个已解析的元素之后,不要忘记增加它。
希望这有帮助!
-Karoly