ヘッダー
@interface XMLParserWrapper : NSObject <NSXMLParserDelegate> {
NSString *searchElementString;
}
- (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **) error ;
- (void)parseXMLFileAtData:(NSData *)data parseError:(NSError **) error ;
@end
実装
@implementation XMLParserWrapper
//URLで解析
- (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **) error {
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
[self parseXMLFile:parser parseError:error];
}
//Dataで解析
- (void)parseXMLFileAtData:(NSData *)data parseError:(NSError **) error {
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
[self parseXMLFile:parser parseError:error];
}
- (void)parseXMLFile:(NSXMLParser *)parser parseError:(NSError **) error {
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
NSError *parseError = [parser parserError];
if (parseError && error) {
*error = parseError;
}
[parser release];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser {
searchElementString = nil;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"取得したい属性名"]) {
searchElementString = [NSString stringWithString:elementName];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"取得したい属性名"]) {
searchElementString = nil;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([searchElementString isEqualToString:@"取得したい属性名"]) {
//stringに取得したい属性の値
}
}
@end
使い方
NSError *parseError = nil;
XMLParserWrapper *parser = [[XMLParserWrapper alloc] init];
[parser parseXMLFileAtData:receivedData parseError:&parseError];
if (parseError) {
//parseエラー
NSLog(@"Parse Error->%@", parseError);
}
0 件のコメント:
コメントを投稿