2012-11-06 6 views
0

XML 파일의 일부 요소에 대한 stringValue에 BOM 문자가 포함되어 있습니다. xml 파일은 UTF-8 인코딩으로 표시됩니다.NSXMLDocument에서 BOM 문자 필터링

일부 문자는 문자열의 시작 부분에 있지만 (일부는 내가 읽은 것과 같아야 함) 문자열의 중간에 있습니다 (XML 파일을 작성한 사람의 형식이 잘못된 문자열 일 수도 있습니다).

내가 가진 파일을 열어 해요 :

NSURL *furl = [NSURL fileURLWithPath:fileName]; 
if (!furl) { 
    NSLog(@"Error: Can't open NML file '%@'.", fileName); 

    return kNxADbReaderTTError; 
} 

NSError *err=nil; 

NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:furl options:NSXMLNodeOptionsNone error:&err]; 

을 그리고있는 요소 이런 식으로 쿼리 :

NSXMLElement *anElement; 
NSString *name; 
... 
NSString *valueString = [[anElement attributeForName:name] stringValue]; 

내 질문

은 다음과 같습니다

은 내가 잘못 파일을 여는 오전? 파일 형식이 잘못 되었습니까? 요소의 문자열 값을 잘못 쿼리합니까? 어떻게 이러한 문자를 필터링 할 수 있습니까?

답변

0

다른 문제를 수정하면서 NSXMLDocument 소스에서 원하지 않는 문자를 필터링하는 비교적 깨끗한 방법을 발견했습니다. 여기에 동일한 문제가 발생하는 경우를 대비해 붙여 넣기 :

@implementation NSXMLDocument (FilterIllegalCharacters) 

    - (NSXMLDocument *)initWithDataAndIgnoreIllegalCharacters:(NSData *)data illegalChars:(NSCharacterSet *)illegalChars error:(NSError **)error{ 
    // -- Then, read the resulting XML string. 
    NSMutableString *str = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

    // -- Go through the XML, only caring about attribute value strings 
    NSMutableArray *charactersToRemove = [NSMutableArray array]; 
    NSUInteger openQuotes = NSNotFound; 
    for (NSUInteger pos = 0; pos < str.length; ++pos) { 
     NSUInteger currentChar = [str characterAtIndex:pos]; 

     if (currentChar == '\"') { 
      if (openQuotes == NSNotFound) { 
       openQuotes = pos; 
      } 
      else { 

       openQuotes = NSNotFound; 
      } 
     } 
     else if (openQuotes != NSNotFound) { 
      // -- If we find an illegal character, we make a note of its position. 
      if ([illegalChars characterIsMember:currentChar]) { 
       [charactersToRemove addObject:[NSNumber numberWithLong:pos]]; 
      } 
     } 
    } 

    if (charactersToRemove.count) { 
     NSUInteger index = charactersToRemove.count; 

     // -- If we have characters to fix, we work thru them backwards, in order to not mess up our saved positions by modifying the XML. 
     do { 
      --index; 

      NSNumber *characterPos = charactersToRemove[index]; 
      [str replaceCharactersInRange:NSMakeRange(characterPos.longValue, 1) withString:@""]; 
     } 
     while (index > 0); 

     // -- Finally we update the data with our corrected version 
     data = [str dataUsingEncoding:NSUTF8StringEncoding]; 
    } 

    return [[NSXMLDocument alloc] initWithData:data options:NSXMLNodeOptionsNone 

    error:error]; 
} 

@end 

원하는 문자 세트를 전달할 수 있습니다. 이 옵션은 XML 문서를 읽지 않기위한 옵션을 없음으로 설정합니다. 당신은 당신 자신의 목적을 위해서 이것을 바꿀 수도 있습니다.

이것은 잘못된 형식의 문자열이있는 속성 문자열의 내용 만 필터링합니다.