2015-01-26 1 views
0

NSXMLParser를 사용하여이 XML을 구문 분석하려고합니다. 내가 지금처럼 XML 파일에 "커피"의 여러 인스턴스를 가지고 :맨 처음 인스턴스를 찾으면 NSXMLParser가 중지됩니다.

… More XML 
<Coffee> 
     <Type Name="Type">Minimum Drinking Amount</Type> 
      </Coffee> 
<Coffee> 
     <Type Name="Type">Maximum Drinking Amount</Type> 
      </Coffee> 
… More XML 

을 이제 NSXMLParser는 "커피"의 첫 번째 인스턴스를 발견하면, 완료 및 XML의 나머지로 이동합니다. 그게 ... 내가하고 싶은게 아니야. "Coffee"의 모든 인스턴스를 읽어야합니다. Objective-C에서 처리하는 방법입니다.

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { 
    NSLog(@"Fired Stick1"); 

    _xmlString = elementName; 

    if ([_xmlString isEqualToString:@"Coffee"]) { 
     NSLog(@"Stick1 Coffee:"); 
    } 

    if ([_xmlString isEqualToString:@"Tea"]) { 
     NSLog(@"Stick1 Tea:"); 
} 

그런 다음 foundCharacters 대리자 :

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 

    if ([_xmlString isEqualToString:@"Coffee"] || [_xmlString isEqualToString:@"Tea"]) { 
     [email protected]"%@ Called", _xmlString); 
    } 
    if (!_coffeeString) { 
     _coffeeString = [[NSMutableString alloc] initWithString:string]; 
    } 
    else { 
     _coffeeString = string; 
    } 

    if (coffeeArray == NULL) { 
     NSLog(@"Stick1 the coffeeArray was null"); 
     coffeeArray = [[NSMutableArray alloc] init]; 
    } 

    //add the returned string into an array 
    [coffeeArray addObject:_coffeeString]; 
    NSLog(@"Stick1 array %@", coffeeArray); 

    // parse the returned data in array 
    NSString *seperate = [coffeeArray componentsJoinedByString:@"\n"]; 
    NSLog(@"Stick1 seperate is %@", seperate); 

    // another parsing 
    NSArray* words = [seperate componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
                          //or use newLineCharecterSet 
    // Take out all of the whitespace like tabs and spaces and new lines 
    _singleName = [words componentsJoinedByString:@""]; 

    NSLog(@"Stick1 final result %@", _singleName); 
} 

기본적으로이 두 번 호출되는,하지만 두 세트의 데이터를 표시하지 않습니다. 커피를 발견하면 커피의 첫 번째 부분 (최소)을 표시하지만 두 번째 커피 (최대)를 표시하지 못합니다.

+0

입니까? – mbm29414

+0

@ mbm29414 내 didEndElement가 비어 있습니다. – John

+0

원하는 데이터 출력은 무엇입니까? – mbm29414

답변

1

여러 문제가 있다고 생각합니다. 하나는 (적어도 제공된 XML과 함께) <Coffee>...</Coffee>은 전체 XML 문서를 정의하므로 처리되지 않은 구문 분석 오류가 발생했을 수 있습니다. 당신은 당신의 NSXMLParserDelegate에 다음 코드를 구현하고보고 어떤 문제가 나타납니다 :

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { 
    NSLog(@"error: %@", parseError); 
} 
- (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError { 
    NSLog(@"error: %@", validationError); 
} 

당신은 또한 당신이 태그 이름의 기반으로 코드에서 트리거/플래그를 설정하려는 문제가 (elementName) 노드의 일부분이지만 실제로는 하위 노드에 포함 된 데이터에 관심이 있습니다.

또한, parser:foundCharacters:는 하나 개의 문자열에 태그의 전체 내용을 반환 보장 하지이다, 그래서 당신은 모두parser:didStartElement:...parser:didEndElement:... 처리 오프 더 많이 있습니다. 그런 다음 parser:foundCharacters:에서 적절한 노드에 있는지 확인하고 을 추가 할 수 있습니다.

여기서이 데이터를 기반으로 시작했다 당신이 제공 한 얻기 위해 몇 가지 예제 코드입니다 :

참고 : 데이터가 조금 애매하기 때문에 난 그냥, 당신이 실제로 원하는에 총을 복용하고 있습니다. 또한, 나는 새로운 Single View App의 App Delegate에서이 작업을 수행했습니다. 이것은 아니요 실제 구현을 수행하는 방법입니다! didEndElement :`방법 어디`파서는

// AppDelegate.m 
#import "AppDelegate.h" 
@interface AppDelegate() <NSXMLParserDelegate> { 

} 
@property (assign, nonatomic) BOOL    inNode; 
@property (strong, nonatomic) NSMutableArray *coffeeArray; 
@property (strong, nonatomic) NSMutableString *coffeeString; 
@property (copy , nonatomic) NSString   *singleName; 
@property (copy , nonatomic) NSString   *xmlString; 
@end 
@implementation AppDelegate 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[[self xml] dataUsingEncoding:NSUTF8StringEncoding]]; 
    parser.delegate  = self; 
    [parser parse]; 
    return YES; 
} 
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { 
    NSLog(@"Fired Stick1"); 

    self.xmlString = elementName; 

    if ([self.xmlString isEqualToString:@"Coffee"]) { 
     NSLog(@"Stick1 Coffee:"); 
     self.coffeeString = [[NSMutableString alloc] init]; 
     self.inNode   = YES; 
    } else if ([self.xmlString isEqualToString:@"Tea"]) { 
     NSLog(@"Stick1 Tea:"); 
     self.coffeeString = [[NSMutableString alloc] init]; 
     self.inNode   = YES; 
    } else { 
     self.inNode   = NO; 
    } 
} 
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    if (self.inNode == YES) { 
     if ([self.xmlString isEqualToString:@"Coffee"] || [self.xmlString isEqualToString:@"Tea"]) { 
      NSLog(@"%@ Called", self.xmlString); 
     } 
     [self.coffeeString appendString:string]; 
    } 
} 
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 
    if ([elementName isEqualToString:@"Coffee"] || [elementName isEqualToString:@"Tea"]) { 
     if (self.coffeeArray == nil) { 
      NSLog(@"Stick1 the coffeeArray was null"); 
      self.coffeeArray = [[NSMutableArray alloc] init]; 
     } 

     //add the returned string into an array 
     [self.coffeeArray addObject:self.coffeeString]; 
     NSLog(@"Stick1 array %@", self.coffeeArray); 

     // parse the returned data in array 
     NSString *seperate = [self.coffeeArray componentsJoinedByString:@"\n"]; 
     NSLog(@"Stick1 seperate is %@", seperate); 

     // another parsing 
     NSArray* words = [seperate componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
     //or use newLineCharecterSet 
     // Take out all of the whitespace like tabs and spaces and new lines 
     _singleName = [words componentsJoinedByString:@""]; 

     NSLog(@"Stick1 final result %@", _singleName); 

    } 
} 
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { 
    NSLog(@"error: %@", parseError); 
} 
- (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError { 
    NSLog(@"error: %@", validationError); 
} 
- (NSString *)xml { 
    NSMutableString *xml = [[NSMutableString alloc] init]; 
    [xml appendString:@"<Document>"]; 
    [xml appendString:@"" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Minimum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Maximum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>\n"]; 
    [xml appendString:@"" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Minimum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Maximum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>\n"]; 
    [xml appendString:@"" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Minimum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Maximum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>\n"]; 
    [xml appendString:@"" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Minimum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Maximum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>\n"]; 
    [xml appendString:@"" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Minimum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Maximum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>\n"]; 
    [xml appendString:@"" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Minimum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>" 
    @"<Coffee>" 
    @" <Type Name=\"Type\">" 
    @" Maximum Drinking Amount" 
    @" </Type>" 
    @"</Coffee>\n"]; 
    [xml appendString:@"</Document>"]; 
    return [xml copy]; 
} 
@end 
관련 문제