2014-02-24 61 views
0

我在做什麼:解析XML以創建NSManagedObject子類並始終解析失敗。Objective-C將XML解析爲NSManagedObjects

代碼在這裏:

NSData* data = [[NSString stringWithUTF8String:answerString.c_str()] dataUsingEncoding:NSUTF8StringEncoding]; 

NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData:data]; 

XMLParser *parser = [[XMLParser alloc] initXMLParser]; 

[nsXmlParser setDelegate:parser]; 

BOOL success = [nsXmlParser parse]; 

其中answerStringstd::string。而且我總是在success旗下獲得NO

我的對象類:

@interface System : NSManagedObject 

@property (nonatomic, retain) NSString * systemFullName; 
@property (nonatomic, retain) NSString * systemShortName; 

@end 

我的解析器頭:

@class System; 

@interface XMLParser : NSObject <NSXMLParserDelegate> 
{ 
    NSMutableString *currentElementValue; 

    System *system; 
} 

- (XMLParser *) initXMLParser; 

與實現

- (XMLParser *) initXMLParser 
{ 
    self = [super init]; 
    return self; 
} 

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
attributes:(NSDictionary *)attributeDict 
{ 
    if ([elementName isEqualToString:@"System"]) 
{ 
    system = [NSEntityDescription insertNewObjectForEntityForName:@"System" 
    inManagedObjectContext:((AppDelegate*)[[UIApplication sharedApplication] 
    delegate]).managedObjectContext]; 
} 
} 

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{ 
    if (!currentElementValue) 
    { 
     currentElementValue = [[NSMutableString alloc] initWithString:string]; 
    } else 
    { 
     [currentElementValue appendString:string]; 
    } 
} 

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 
{ 
    NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] 
delegate]).managedObjectContext; 

if ([elementName isEqualToString:@"System"]) 
{ 
    [context save:nil]; 
    system = nil; 
} 

if ([elementName isEqualToString:@"systemFullName"]) 
{ 
    system.systemFullName = currentElementValue; 
} 

if ([elementName isEqualToString:@"systemShortName"]) 
{ 
    system.systemShortName = currentElementValue; 
} 
} 

任何想法?

我偶然發現,當方法didEndElement查找第一個對象的結束,只是XMLParser的停止工作,錯誤111

+0

解析時出現了什麼錯誤? – Leena

回答

0

我解決這個問題。取而代之的是XML這樣的格式:

<System> 
    <systemFullName>aaaa</systemFullName> 
    <systemShortName>a</systemShortName> 
</System> 
<System> 
    <systemFullName>bbbb</systemFullName> 
    <systemShortName>b</systemShortName> 
</System> 

我用這個格式:

<startXML> 
    <System> 
     <systemFullName>aaaa</systemFullName> 
     <systemShortName>a</systemShortName> 
    </System> 
    <System> 
     <systemFullName>bbbb</systemFullName> 
     <systemShortName>b</systemShortName> 
    </System> 
</startXML> 

他是一樣的,只是用文件的開頭的開始和結束標記和結束。嘆。