Created
November 6, 2011 19:30
-
-
Save indragiek/1343350 to your computer and use it in GitHub Desktop.
libxml2 parsing code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (BOOL)parse | |
{ | |
NSLog(@"Began parsing"); | |
[inputStream open]; | |
/* Read 4 bytes initially to create the push parser context and begin parsing */ | |
NSStreamStatus status = [inputStream streamStatus]; | |
uint8_t buf[4]; | |
NSInteger bytesRead; | |
while (status != NSStreamStatusAtEnd) { | |
if (status == NSStreamStatusError) { | |
[self closeInputStream]; | |
return NO; | |
} | |
if ([inputStream hasBytesAvailable]) { | |
bytesRead = [inputStream read:buf maxLength:4]; | |
break; | |
} | |
} | |
if (!bytesRead) { | |
[self closeInputStream]; | |
return NO; | |
} | |
ctx = xmlCreatePushParserCtxt(&saxHandlerStruct, NULL, (const void*)buf, (int)bytesRead, NULL); | |
int options = XML_PARSE_RECOVER|XML_PARSE_NOENT|XML_PARSE_DTDLOAD; | |
xmlCtxtUseOptions(ctx, options); | |
while ([inputStream streamStatus] != NSStreamStatusAtEnd) { | |
if ([inputStream streamStatus] == NSStreamStatusError) { | |
[self closeInputStream]; | |
return NO; | |
} | |
/* If there are bytes available then read a chunk of size PAGE_SIZE (usually 4KB) */ | |
if ([inputStream hasBytesAvailable]) { | |
uint8_t chunk[PAGE_SIZE]; | |
NSInteger length = [inputStream read:chunk maxLength:PAGE_SIZE]; | |
/* If the input stream has nothing left to read then terminate after this chunk */ | |
BOOL terminate = [inputStream streamStatus] == NSStreamStatusAtEnd; | |
if (xmlParseChunk(ctx, (const void*)chunk, (int)length, terminate)) { | |
/* If an error is encountered then do clean up and return */ | |
[self closeInputStream]; | |
return NO; | |
} | |
} | |
} | |
NSLog(@"Finished parsing!"); | |
[self closeInputStream]; | |
return YES; | |
} | |
- (void)closeInputStream | |
{ | |
[inputStream close]; | |
inputStream = nil; | |
if (ctx) { | |
xmlFreeParserCtxt(ctx); | |
xmlCleanupParser(); | |
ctx = NULL; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment