我今天早些时候已经写了一个简单的 NSXMLParser 示例,所以我就拿它来解析你描述的 XML。
此处的工作示例项目:https ://github.com/erikt/ETParseIntuitSOExample
NSXMLParser 委托就是您所要求的。这是标题:
#import <Foundation/Foundation.h>
@interface ETIntuitParser : NSObject<NSXMLParserDelegate>
+ (NSDictionary *)parseIntuitXML:(NSString *)xml;
@end
和实施:
#import "ETIntuitParser.h"
@interface ETIntuitParser ()
@property NSUInteger dataColNumber;
@property (copy,nonatomic) NSString *dataKey;
@property (strong,nonatomic) NSMutableString *currentElementValue;
@property (strong,nonatomic) NSMutableDictionary *resultDict;
@end
@implementation ETIntuitParser
+ (NSDictionary *)parseIntuitXML:(NSString *)xml {
ETIntuitParser *intuitParser = [[ETIntuitParser alloc] init];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
[xmlParser setDelegate:intuitParser];
BOOL success = [xmlParser parse];
if (success) {
return [NSDictionary dictionaryWithDictionary:intuitParser.resultDict];
} else {
NSLog(@"Error parsing login information");
return nil;
}
}
#pragma mark - NSXMLParserDelegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"Report"]) {
if (!self.resultDict) {
self.resultDict = [NSMutableDictionary dictionary];
}
return;
}
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (!self.currentElementValue) {
self.currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
[self.currentElementValue appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"DataRow"]) {
self.dataColNumber = 0;
}
if ([elementName isEqualToString:@"ColData"]) {
NSString *trimmedValue = [self.currentElementValue stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (self.dataColNumber == 0) {
self.dataKey = trimmedValue;
self.dataColNumber++;
} else {
[self.resultDict setObject:trimmedValue forKey:self.dataKey];
}
}
self.currentElementValue = nil;
}
@end
我刚刚用 NSLog 打印出结果字典(在视图控制器的 viewDidLoad 中不少于 ... ),结果是:
2012-11-07 00:21:22.409 ETParseIntuitSOExample[66941:c07] {
"Accounts Payable" = 653653;
"Accounts Receivable" = 674532;
"Checking/Savings" = 12345345;
Equity = 45363;
"Fixed Assets" = 63545534;
"Long Term Liabilities" = "553797.26";
"Other Assets" = 325465;
"Other Current Assets" = 423546;
"Other Current Liabilities" = "910596.75";
}
我不知道您是否需要 XML 结构中的列标题信息,但这应该很容易添加。