Skip to content

Instantly share code, notes, and snippets.

@indragiek
Created November 6, 2011 19:30
Show Gist options
  • Save indragiek/1343350 to your computer and use it in GitHub Desktop.
Save indragiek/1343350 to your computer and use it in GitHub Desktop.
libxml2 parsing code
- (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