1

我对我应该如何为我当前的 iPhone 应用程序项目循环遍历 XML 元素感到非常困惑。我将展示我的代码,然后澄清我的问题。

这是我正在使用的示例 XML:

<restaurant_details>
    <total_results>90</total_results>
    <restaurant>
        <name>Through the Garden</name>
        <distance_from_current_location>0.55</distance_from_current_location>
        <restaurant_id>123</restaurant_id>
        <longitude>-84.373734</longitude>
        <latitude>39.258606</latitude>
        <address>10738 Kenwood Rd  | cincinnati ,OH | 45242</address>
        <phone_number>513-791-2199</phone_number>
        <restaurant_type>General</restaurant_type>
    </restaurant>
</restaurant_details>

获取我的表的数据:

- (void)get_table_data {
    NSString *day = [self dateInFormat:@"%A"];

    NSLog (@"At get_table_data");

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.url.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection) {
        NSLog (@"At connection");
        receivedData = [NSMutableData data];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //      NSString *theXML = [[NSString alloc] initWithBytes: [myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding];
    //      NSLog(@"%@",theXML);[theXML release];   
    if(parser){
        parser = nil;
    }

    parser = [[NSXMLParser alloc] initWithData: receivedData];
    [parser setDelegate: self];
    [parser setShouldResolveExternalEntities: YES];
    [parser parse];
}

我的解析器代码:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
    NSLog (@"At parser");
    currentElement = elementName;

    if ([currentElement isEqualToString:@"restaurant_details"]) {
        if ([currentElement isEqualToString:@"total_results"]) {
            //NSLog(@"Element: %@", currentElement);
        }else if ([currentElement isEqualToString:@"restaurant"]) {
            restaurantObj = [[DOR_RestaurantClass alloc]init];
        }
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    if([currentElement isEqualToString:@"name"]) {
        restaurantObj.name=[NSString stringWithFormat:@"%@",string];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    if([currentElement isEqualToString:@"distance_from_current_location"]) {
        restaurantObj.distance=[NSString stringWithFormat:@"%@",string];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    if([currentElement isEqualToString:@"restaurant_id"]) {
        restaurantObj.restId=[NSString stringWithFormat:@"%@",string];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    if([currentElement isEqualToString:@"address"]) {
        NSArray *stringArray = [string componentsSeparatedByString:@" | "];
        restaurantObj.address=[stringArray objectAtIndex:0];
        restaurantObj.address2=[stringArray objectAtIndex:1];
        restaurantObj.address3=[stringArray objectAtIndex:2];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    if([currentElement isEqualToString:@"phone_number"]) {
        restaurantObj.phone=[NSString stringWithFormat:@"%@",string];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    if([currentElement isEqualToString:@"description"]) {
        restaurantObj.description=[NSString stringWithFormat:@"%@",string];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    if([currentElement isEqualToString:@"image_url"]) {
        restaurantObj.image=[NSString stringWithFormat:@"%@",string];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    if([currentElement isEqualToString:@"restaurant_type"]) {
        //restaurantObj.Name=[NSString stringWithFormat:@"%@",string];
        //NSLog(@"Name to be saved in Array :- %@",string);
    }
    NSLog (@"At parser2");
    if(!currentElementValue)
        currentElementValue=[[NSMutableString alloc] initWithString:string];
    else
        [currentElementValue appendString:string];
    NSLog(@"the parser just found this text in a tag:%@",string);
}

-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qualifiedName {
    NSLog(@"Current element in End Element Category:- %@",currentElement);
    if([elementName isEqualToString:@"restaurant"]) {
        [listItems addObject:restaurantObj];
        NSLog(@"Array: %@", listItems);
    }else{
        currentElementValue=nil;
    }

}

这是我的餐厅课程的 .h:

#import <Foundation/Foundation.h>

@interface DOR_RestaurantClass : NSObject

@property (nonatomic, retain) NSString *restId;
@property (nonatomic, retain) NSString *image;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *distance;
@property (nonatomic, retain) NSString *address;
@property (nonatomic, retain) NSString *address2;
@property (nonatomic, retain) NSString *address3;
@property (nonatomic, retain) NSString *phone;
@property (nonatomic, retain) NSString *expires;

@end

我的.m:

#import "DOR_RestaurantClass.h"

@implementation DOR_RestaurantClass
@synthesize restId;
@synthesize image;
@synthesize name;
@synthesize description;
@synthesize distance;
@synthesize address;
@synthesize address2;
@synthesize address3;
@synthesize phone;
@synthesize expires;

@end

我正在获取我的数据等等,所以这不是问题。我的问题是:在我的 XML 数据中有多个“餐厅”标签,我如何对 XML 进行排序以便将餐厅数据保存在一起?我来自 PHP,所以我会在餐厅标签上做一个 foreach,但我不确定 NSXMLParser 应该如何保持数据分离。最后,我会将这些信息放入 NSMutableArray 中。我只是不知道从哪里开始,也找不到任何这样做的好例子。非常感谢任何和所有帮助。

这已更新

我的数组listItems(NSMutableArray) 是null当我将它打印到NSLog.

4

1 回答 1

2

首先创建一个仅包含 .h 和 .m 文件的 Obj c 类。并在其中创建一些具有名称、距离、经度、纬度等属性的 NSString 变量。

现在,代码部分:-

在 didStartElement

在餐厅标签中创建一个我刚刚告诉你创建的类的对象(初始化对象):-

currentElement = elementName;

    if([currentElement isEqualToString:@"restaurant"]) {
        classObj = [[MyRestaurentClass alloc]init];
    }

现在在 foundCharacters 中找到像这样的其他标签:-

if([currentElement isEqualToString:@"name"]) {
        classObj.Name=[NSString stringWithFormat:@"%@",string];
        NSLog(@"Name to be saved in Array :- %@",string);
    }
    if ( [currentElement isEqualToString:@"longitude"])
    {
        classObj.longitude =[NSString stringWithFormat:@"%@",string];            
    }
}

现在是 didEneElement 的最后一部分:-

在 Parser Class 中创建一个 MutubaleArray 并在 didEndElement 中的该数组中添加 classObj :-

if([elementName isEqualToString:@"restaurent"]) {
        NSLog(@"Current element in End Element Category:- %@",currentElement);
        [ObjectsMutableArray addObject:classObj];

    }

就这样。你完成了解析..

更新

首先,您不必在 If 循环中这样写,即:-

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{
    NSLog (@"At parser");
    currentElement = elementName;

    if ([currentElement isEqualToString:@"restaurant_details"]) {
        if ([currentElement isEqualToString:@"total_results"]) {
            //NSLog(@"Element: %@", currentElement);
        }else if ([currentElement isEqualToString:@"restaurant"]) {
            restaurantObj = [[DOR_RestaurantClass alloc]init];
        }
    }
}

我为 didStartElement 写的答案足够了,因为每个标签都调用了 didStartElement。

请参阅一旦您创建了一个具有符合您的 XML 的 NSStrings 的类。只需创建该类的对象并在 didStartElement 中对其进行初始化。在 foundCharacters 中,您将根据 If 条件循环在 classObject 变量中添加所需数据。每当 XMlParser 进入</restaurent>Tag 时,它就会进入 didEndElement 方法,您只需像在 didEndElement 中那样将该类对象(对象)放入该数组中。

好的关于您的 NSMutableArray,您是否像这样在 didStartDocument 中初始化了数组:-

  • (void)parserDidStartDocument:(NSXMLParser *)parser{ listItems = [[NSMutableArray alloc]init]; }

我已更改上述代码,因此请再次仔细阅读整个答案。如果你还有任何疑问给我发短信...

于 2012-04-09T06:13:05.330 回答