我不知道我在做什麼錯。我有一個URL導致一個XML樹,看起來像:XMLParser建議
<result>
...
<title>
...
</title>
<body>
...
</body>
...
</result>
我只需要解析文件,並獲得標題和正文。這裏是我的object.h:
#import <Foundation/Foundation.h>
@interface Object : NSObject
{
NSString *title;
NSString *description;
}
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *description;
@end
這裏是Object.m:
#import "Object.h"
@implementation Object
@synthesize title, description;
-(void) dealloc
{
[title release];
[description release];
[super dealloc];
}
@end
這裏是我的XMLParser.h:
#import <Foundation/Foundation.h>
#import "Object.h"
@interface XMLParser : NSObject <NSXMLParserDelegate>
{
NSMutableString *currentNodeContent;
NSMutableArray *arrayOfObjects;
NSXMLParser *parser;
Object *currentObject;
}
@property (readonly, retain) NSMutableArray *arrayOfObjects;
-(id) loadXMLbyURL:(NSString *)urlString;
@end
最後,XMLParser.m:
#import "XMLParser.h"
#import "Object.h"
@implementation XMLParser
@synthesize arrayOfObjects;
-(id) loadXMLbyURL:(NSString *)urlString
{
arrayOfObjects = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [[[NSData alloc] initWithContentsOfURL:url] autorelease];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
return self;
}
-(void) dealloc
{
[parser release];
[super dealloc];
}
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:@"result"])
{
currentObject = [Object alloc];
}
}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"title"])
{
currentObject.title = currentNodeContent;
}
if([elementName isEqualToString:@"body"])
{
currentObject.description = currentNodeContent;
}
if([elementName isEqualToString:@"result"])
{
[arrayOfObjects addObject:currentObject];
[currentObject release];
currentObject = nil;
[currentNodeContent release];
currentNodeContent = nil;
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
@end
在我的主代碼中,我調用了XML pa RSER這樣的:
xmlParser = [[XMLParser alloc] loadXMLbyURL:@"www.websiteWithXML.com"];
但是沒有什麼是被放入我的arrayOfObjects(我知道這是因爲,當我告訴一個tableview中有儘可能多的行作爲我的陣列,沒有行)。
請幫忙!!!先謝謝你!
爲什麼你給你的數組只讀屬性......?嘗試非原子 –
我遵循本教程http://www.theappcodeblog.com/2011/05/09/parsing-xml-in-an-iphone-app-tutorial/ – jisturiz
它的工作很好,但當我試圖調整它爲我使用...它不工作! – jisturiz