Ejemplo n.º 1
0
mzpSAXHandler::mzpSAXHandler()
{
	fptr = NULL;
	m_bGZCompression = false;
	fptr = NULL;
	m_parser = XML_ParserCreate(NULL);
	XML_SetUserData(m_parser, this);
	XML_SetElementHandler(m_parser, mzp_startElementCallback, mzp_endElementCallback);
	XML_SetCharacterDataHandler(m_parser, mzp_charactersCallback);
}
Ejemplo n.º 2
0
XmlParser::XmlParser(XmlContentHandler& handler)
    : handler_(handler)
{
    parser_ = XML_ParserCreateNS(0, '\t');
    XML_SetUserData(parser_, static_cast<void*>(this));
    XML_SetStartElementHandler(parser_, StartElementHandler);
    XML_SetEndElementHandler(parser_, EndElementHandler);
    XML_SetCharacterDataHandler(parser_, CharacterDataHandler);
    error_msg_ = "Failed to parse XML.";
}
Ejemplo n.º 3
0
QgsGPSData* QgsGPSData::getData( const QString& fileName )
{
  // if the data isn't there already, try to load it
  if ( dataObjects.find( fileName ) == dataObjects.end() )
  {
    QFile file( fileName );
    if ( !file.open( QIODevice::ReadOnly ) )
    {
      QgsLogger::warning( QObject::tr( "Couldn't open the data source: %1" ).arg( fileName ) );
      return 0;
    }
    QgsGPSData* data = new QgsGPSData;
    QgsDebugMsg( "Loading file " + fileName );
    QgsGPXHandler handler( *data );
    bool failed = false;

    // SAX parsing
    XML_Parser p = XML_ParserCreate( NULL );
    XML_SetUserData( p, &handler );
    XML_SetElementHandler( p, QgsGPXHandler::start, QgsGPXHandler::end );
    XML_SetCharacterDataHandler( p, QgsGPXHandler::chars );
    long int bufsize = 10 * 1024 * 1024;
    char* buffer = new char[bufsize];
    int atEnd = 0;
    while ( !file.atEnd() )
    {
      long int readBytes = file.read( buffer, bufsize );
      if ( file.atEnd() )
        atEnd = 1;
      if ( !XML_Parse( p, buffer, readBytes, atEnd ) )
      {
        QgsLogger::warning( QObject::tr( "Parse error at line %1 : %2" )
                            .arg( XML_GetCurrentLineNumber( p ) )
                            .arg( XML_ErrorString( XML_GetErrorCode( p ) ) ) );
        failed = true;
        break;
      }
    }
    delete [] buffer;
    XML_ParserFree( p );
    if ( failed )
      return 0;

    data->setNoDataExtent();

    dataObjects[fileName] = std::pair<QgsGPSData*, unsigned>( data, 0 );
  }
  else
    QgsDebugMsg( fileName + " is already loaded" );

  // return a pointer and increase the reference count for that file name
  DataMap::iterator iter = dataObjects.find( fileName );
  ++( iter->second.second );
  return ( QgsGPSData* )( iter->second.first );
}
Ejemplo n.º 4
0
xml_t * XSD_Variable_LoadFromHandle(FILE *f, int filelen) {
#else
xml_t * XSD_Variable_LoadFromHandle(vfsfile_t *v, int filelen) {
	vfserrno_t err;
#endif
    xml_variable_t *document;
    XML_Parser parser = NULL;
    int len;
	int pos = 0;
    char buf[XML_READ_BUFSIZE];
    xml_parser_stack_t parser_stack;

    // create blank document
    document = (xml_variable_t *) Q_malloc(sizeof(xml_variable_t));
    XSD_Variable_Init(document);

    // initialize XML parser
    parser = XML_ParserCreate(NULL);
    if (parser == NULL)
        goto error;
    XML_SetStartElementHandler(parser, OnStartElement);
    XML_SetEndElementHandler(parser, OnEndElement);
    XML_SetCharacterDataHandler(parser, OnCharacterData);

    // prepare user data
    XSD_InitStack(&parser_stack);
    parser_stack.document = (xml_t *) document;
    XML_SetUserData(parser, &parser_stack);

#ifndef WITH_FTE_VFS
    while ((len = fread(buf, 1, min(XML_READ_BUFSIZE, filelen-pos), f)) > 0)
#else
    while ((len = VFS_READ(v, buf, min(XML_READ_BUFSIZE, filelen-pos), &err)) > 0)
#endif
    {
        if (XML_Parse(parser, buf, len, 0) != XML_STATUS_OK)
            goto error;

		pos += len;
    }
    if (XML_Parse(parser, NULL, 0, 1) != XML_STATUS_OK)
        goto error;

    XML_ParserFree(parser);

    return (xml_t *) document;

error:

    if (parser)
        XML_ParserFree(parser);
    XSD_Variable_Free((xml_t *)document);

    return NULL;
}
Ejemplo n.º 5
0
int gamelist_load(void)
{
	XML_Parser parser = XML_ParserCreate(NULL);
	FILE *f;
	int depth = 0, done;
	static char buf[BUFSIZ];

	curgame = -1;
	numgames = 0;
	games = (M1GameT *)NULL;	// realloc() will become malloc() if ptr is NULL, which is handy

	f = fopen("m1.xml", "r");
	if (!f)
	{
		return 0;
	}

	XML_SetUserData(parser, &depth);
	XML_SetElementHandler(parser, startElement, endElement);
	XML_SetCharacterDataHandler(parser, charData);
	XML_SetUnknownEncodingHandler(parser, unkEncodingHandler, NULL);

	xml_state = XML_INVALID;
		
	do 
	{
		unsigned int len = fread(buf, 1, sizeof(buf), f);

		done = (len < sizeof(buf));

		if (!XML_Parse(parser, buf, len, done))
		{
			printf("XML parse error %s at line %d (m1.xml)\n",
				XML_ErrorString(XML_GetErrorCode(parser)),
				XML_GetCurrentLineNumber(parser));

			// clean up
			XML_ParserFree(parser);
			if (games)
			{
				free(games);
				games = (M1GameT *)NULL;
			}
			return 0;
		}

	} while (!done);

	XML_ParserFree(parser);

	fclose(f);

//	printf("Finished loading, %d games\n", numgames);
	return numgames;
}
Ejemplo n.º 6
0
BOOLEAN ReadInArmyCompositionInfo(STR fileName)
{
	HWFILE		hFile;
	UINT32		uiBytesRead;
	UINT32		uiFSize;
	CHAR8 *		lpcBuffer;
	XML_Parser	parser = XML_ParserCreate(NULL);

	compositionParseData pData;

	// Open weapons file
	hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE );
	if ( !hFile )
		return( FALSE );

	uiFSize = FileGetSize(hFile);
	lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1);

	//Read in block
	if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) )
	{
		MemFree(lpcBuffer);
		return( FALSE );
	}

	lpcBuffer[uiFSize] = 0; //add a null terminator

	FileClose( hFile );


	XML_SetElementHandler(parser, compositionStartElementHandle, compositionEndElementHandle);
	XML_SetCharacterDataHandler(parser, compositionCharacterDataHandle);


	memset(&pData,0,sizeof(pData));
	XML_SetUserData(parser, &pData);
	NUM_ARMY_COMPOSITIONS = 0;

	if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE))
	{
		CHAR8 errorBuf[511];

		sprintf(errorBuf, "XML Parser Error in ArmyComposition.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser));
		LiveMessage(errorBuf);

		MemFree(lpcBuffer);
		return FALSE;
	}

	MemFree(lpcBuffer);

	XML_ParserFree(parser);

	return TRUE;
}
Ejemplo n.º 7
0
TinyDomElement* TinyDom::parse(std::istream& istr) {

  XML_Parser parser = XML_ParserCreate(0);
  TinyDomParser tdparser;

  XML_SetUserData(parser, &tdparser);
  XML_SetCharacterDataHandler(parser, characterDataHandler);
  XML_SetElementHandler(parser, startElementHandler, endElementHandler);
  XML_SetCommentHandler(parser, commentHandler);
  XML_SetProcessingInstructionHandler(parser, processingInstructionHandler);
  XML_SetXmlDeclHandler(parser, xmlDeclHandler);
  XML_SetDefaultHandler(parser, defaultHandler);
  XML_SetDoctypeDeclHandler(parser, startDoctypeDeclHandler, endDoctypeDeclHandler);

  try {

    while (1) {
      void* buf = XML_GetBuffer(parser, 1024);
      if (!buf) {
	throw std::runtime_error("out of memory!");
      }
      istr.read((char*)buf, 1024);
	  std::streamsize len = istr.gcount();
      if (istr.fail() && !istr.eof()) {
	throw std::runtime_error("failed IO");
      }
      bool isFinal = (istr.eof() || len < 1024);
      if (! XML_ParseBuffer(parser, len, isFinal)) {
	std::ostringstream ostr;
	ostr << "parse error at line " << XML_GetErrorLineNumber(parser)
	     << ", column " << XML_GetErrorColumnNumber(parser) << ": "
	     << XML_ErrorString(XML_GetErrorCode(parser));
	throw std::runtime_error(ostr.str());
				 
      }
      if (isFinal) {
	break;
      }
    }
	
    XML_ParserFree(parser);
	
  } catch (...) {

    //std::cerr << "Got exception: " << e.what() << "\n";

    if (parser) { XML_ParserFree(parser); }
    delete tdparser.rootElement;
    throw;

  }

  return tdparser.rootElement;

}
Ejemplo n.º 8
0
int
main(int argc, char **argv)
{
    XML_Parser parser;

    size_t i;
    size_t j;

    nst_cfg_allocator = nst_mem_stat_register("NST CFG");

    parser = XML_ParserCreate(NULL);
    expat_stack_top->parser = parser;

    if(!parser) {
        assert(0 && "Cannot allocate memory during XML_ParserCreate\n");
        return -1;
    }

    for(i = 0;
            i < sizeof(xml_test_strings) / sizeof(const char *);
            i++) {
        const char *xml_test_string = xml_test_strings[i];
        enum XML_Status xml_status;

        XML_SetStartElementHandler(parser, root_start_handler);
        XML_SetEndElementHandler(parser, root_end_handler);
        XML_SetCharacterDataHandler(parser, root_char_handler);
        XML_SetUserData(parser, (void*)&expat_stack_top);

        for(j = 0; xml_test_string[j]; j++) {
            xml_status = XML_Parse(parser, xml_test_string+j, 1, 0);
            if(xml_status != XML_STATUS_OK) {
                fprintf(stderr, "Parse error at line %lu: %s\n",
                        XML_GetCurrentLineNumber(parser),
                        XML_ErrorString(XML_GetErrorCode(parser)));
                return -1;
            }
        }

        xml_status = XML_Parse(parser, NULL, 0, 1);
        if(xml_status != XML_STATUS_OK) {
            fprintf(stderr, "Parse error at line %lu: %s\n",
                    XML_GetCurrentLineNumber(parser),
                    XML_ErrorString(XML_GetErrorCode(parser)));
            return -1;
        }

        XML_ParserReset(parser, NULL);
    };

    XML_ParserFree(parser);

    assert(nst_mem_stat_get_allocated_nbytes(nst_cfg_allocator.data) == 0);
    return 0;
}
Ejemplo n.º 9
0
/*
 * Public interface
 */
clish_xmldoc_t *clish_xmldoc_read(const char *filename)
{
	clish_xmldoc_t *doc;
	struct stat sb;
	int fd;
	char *buffer;
	XML_Parser parser;
	int rb;

	doc = malloc(sizeof(clish_xmldoc_t));
	if (!doc)
		return NULL;
	memset(doc, 0, sizeof(clish_xmldoc_t));
	doc->filename = strdup(filename);
	parser = XML_ParserCreate(NULL);
	if (!parser)
		goto error_parser_create;
	XML_SetUserData(parser, doc);
	XML_SetCharacterDataHandler(parser, clish_expat_chardata_handler);
	XML_SetElementHandler(parser,
		clish_expat_element_start,
		clish_expat_element_end);

	fd = open(filename, O_RDONLY);
	if (fd < 0)
		goto error_open;
	fstat(fd, &sb);
	buffer = malloc(sb.st_size+1);
	rb = read(fd, buffer, sb.st_size);
	if (rb < 0) {
		close(fd);
		goto error_parse;
	}
	buffer[sb.st_size] = 0;
	close(fd);

	if (!XML_Parse(parser, buffer, sb.st_size, 1))
		goto error_parse;

	XML_ParserFree(parser);
	free(buffer);

	return doc;

error_parse:
	free(buffer);

error_open:
	XML_ParserFree(parser);

error_parser_create:
	clish_xmldoc_release(doc);

	return NULL;
}
Ejemplo n.º 10
0
Archivo: xmlstream.c Proyecto: 2px/curl
int main(void)
{
  CURL *curl_handle;
  CURLcode res;
  XML_Parser parser;
  struct ParserStruct state;

  /* Initialize the state structure for parsing. */
  memset(&state, 0, sizeof(struct ParserStruct));
  state.ok = 1;

  /* Initialize a namespace-aware parser. */
  parser = XML_ParserCreateNS(NULL, '\0');
  XML_SetUserData(parser, &state);
  XML_SetElementHandler(parser, startElement, endElement);
  XML_SetCharacterDataHandler(parser, characterDataHandler);

  /* Initialize a libcurl handle. */
  curl_global_init(CURL_GLOBAL_ALL ^ CURL_GLOBAL_SSL);
  curl_handle = curl_easy_init();
  curl_easy_setopt(curl_handle, CURLOPT_URL,
                   "http://www.w3schools.com/xml/simple.xml");
  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, parseStreamCallback);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)parser);

  printf("Depth   Characters   Closing Tag\n");

  /* Perform the request and any follow-up parsing. */
  res = curl_easy_perform(curl_handle);
  if(res != CURLE_OK) {
    fprintf(stderr, "curl_easy_perform() failed: %s\n",
            curl_easy_strerror(res));
  }
  else if(state.ok) {
    /* Expat requires one final call to finalize parsing. */
    if(XML_Parse(parser, NULL, 0, 1) == 0) {
      int error_code = XML_GetErrorCode(parser);
      fprintf(stderr, "Finalizing parsing failed with error code %d (%s).\n",
              error_code, XML_ErrorString(error_code));
    }
    else {
      printf("                     --------------\n");
      printf("                     %lu tags total\n", state.tags);
    }
  }

  /* Clean up. */
  free(state.characters.memory);
  XML_ParserFree(parser);
  curl_easy_cleanup(curl_handle);
  curl_global_cleanup();

  return 0;
}
Ejemplo n.º 11
0
int
_xml_papi_hwi_setup_all_presets( char *arch, hwi_dev_notes_t * notes )
{
	int done = 0;
	FILE *fp = fopen( "./papi_events.xml", "r" );
	XML_Parser p = XML_ParserCreate( NULL );

	if ( !p ) {
		PAPIERROR( "Couldn't allocate memory for XML parser." );
		fclose(fp);
		return ( PAPI_ESYS );
	}
	XML_SetElementHandler( p, _xml_start, _xml_end );
	XML_SetCharacterDataHandler( p, _xml_content );
	if ( fp == NULL ) {
		PAPIERROR( "Error opening Preset XML file." );
		fclose(fp);
		return ( PAPI_ESYS );
	}

	xml_arch = arch;

	do {
		int len;
		void *buffer = XML_GetBuffer( p, BUFFSIZE );

		if ( buffer == NULL ) {
			PAPIERROR( "Couldn't allocate memory for XML buffer." );
			fclose(fp);
			return ( PAPI_ESYS );
		}
		len = fread( buffer, 1, BUFFSIZE, fp );
		if ( ferror( fp ) ) {
			PAPIERROR( "XML read error." );
			fclose(fp);
			return ( PAPI_ESYS );
		}
		done = feof( fp );
		if ( !XML_ParseBuffer( p, len, len == 0 ) ) {
			PAPIERROR( "Parse error at line %d:\n%s",
					   XML_GetCurrentLineNumber( p ),
					   XML_ErrorString( XML_GetErrorCode( p ) ) );
			fclose(fp);
			return ( PAPI_ESYS );
		}
		if ( error ) {
			fclose(fp);
			return ( PAPI_ESYS );
		}
	} while ( !done );
	XML_ParserFree( p );
	fclose( fp );
	return ( PAPI_OK );
}
Ejemplo n.º 12
0
static void driver_info_parse(DriverInfo* thiz, char* buffer, size_t length)
{
	XML_Parser parser = XML_ParserCreate(NULL);
	XML_SetUserData(parser, thiz);
	XML_SetElementHandler(parser, on_start, on_end);
	XML_SetCharacterDataHandler(parser, on_text);
    XML_Parse(parser, buffer, length, TRUE);
	XML_ParserFree(parser);

	return;
}
ExpatParser::ExpatParser() :
    mHandler(NULL)
{
    mExpat = XML_ParserCreate(NULL);
    if (mExpat) {
        XML_SetUserData(mExpat, this);
        XML_SetDoctypeDeclHandler(mExpat, startDoctypeWrapper, endDoctypeWrapper);
        XML_SetElementHandler(mExpat, startElementWrapper, endElementWrapper);
        XML_SetCharacterDataHandler(mExpat, charactersWrapper);
    }
}
Ejemplo n.º 14
0
PRIVATE void HTXML_setHandlers (XML_Parser me)
{
    XML_SetElementHandler(me, XML_startElement, XML_endElement);
    XML_SetCharacterDataHandler(me, XML_characterData);
    XML_SetProcessingInstructionHandler(me, XML_processingInstruction);
    XML_SetDefaultHandler(me, XML_default);
    XML_SetUnparsedEntityDeclHandler(me, XML_unparsedEntityDecl);
    XML_SetNotationDeclHandler(me, XML_notationDecl);
    XML_SetExternalEntityRefHandler(me, XML_externalEntityRef);
    XML_SetUnknownEncodingHandler(me, XML_unknownEncoding, NULL);
}
Ejemplo n.º 15
0
xode xode_from_file(char *file)
{
    XML_Parser p;
    xode *x, node; /* pointer to an xmlnode */
    char buf[BUFSIZ];
    int done, fd, len;
    char _file[1000];

    if(NULL == file)
        return NULL;

    /* perform tilde expansion */
    if(*file == '~')
    {
        char *env = getenv("HOME");
        if(env != NULL)
            snprintf((char*)_file, 1000, "%s%s", env, file + 1);
        else
            snprintf((char*)_file, 1000, "%s", file);
    }
    else
    {
        snprintf((char*)_file, 1000, "%s", file);
    }

    fd = open((char*)&_file,O_RDONLY);
    if(fd < 0)
        return NULL;

    x = malloc(sizeof(void *));

    *x = NULL; /* pointer to NULL */
    p = XML_ParserCreate(NULL);
    XML_SetUserData(p, x);
    XML_SetElementHandler(p, _xode_expat_startElement, _xode_expat_endElement);
    XML_SetCharacterDataHandler(p, _xode_expat_charData);
    do{
        len = read(fd, buf, BUFSIZ);
        done = len < BUFSIZ;
        if(!XML_Parse(p, buf, len, done))
        {
            /*            jdebug(ZONE,"xmlnode_file_parseerror: %s",(char *)XML_ErrorString(XML_GetErrorCode(p)));*/
            xode_free(*x);
            *x = NULL;
            done = 1;
        }
    }while(!done);

    node = *x;
    XML_ParserFree(p);
    free(x);
    close(fd);
    return node; /* return the xmlnode x points to */
}
Ejemplo n.º 16
0
static void
run_character_check(XML_Char *text, XML_Char *expected)
{
    CharData storage;

    CharData_Init(&storage);
    XML_SetUserData(parser, &storage);
    XML_SetCharacterDataHandler(parser, accumulate_characters);
    if (XML_Parse(parser, text, strlen(text), 1) == XML_STATUS_ERROR)
        xml_failure(parser);
    CharData_CheckXMLChars(&storage, expected);
}
Ejemplo n.º 17
0
static void got_api(struct evhttp_request* req, void* userdata)
{
    struct req_data* d = (struct req_data*) userdata;

    if(req->response_code != 200)
    {
        evhttp_send_error(d->req, 500, "Internal Server Error");
        free_req_data(&d);
        fprintf(stderr, "info.c:got_api(): api returned http status %d\n", (int)(req->response_code));
        return;
    }

    XML_Parser parser = XML_ParserCreate(NULL);
    int done;
    int depth = 0;
    XML_SetUserData(parser, d);
    XML_SetElementHandler(parser, startElement, endElement);
    XML_SetCharacterDataHandler(parser, xmlData);

    char buf[4096];
    int buflen;
    while((buflen = evbuffer_remove(req->input_buffer, buf, 4096)) > 0)
    {
        if(XML_Parse(parser, buf, buflen, 0) == XML_STATUS_ERROR)
        {
            evhttp_send_error(d->req, 500, "Internal Server Error");
            free_req_data(&d);
            fprintf(stderr, "info.c:got_api(): error parsing xml: %s\n", XML_ErrorString(XML_GetErrorCode(parser)));
            return;
        }
    }
    XML_ParserFree(parser);

    // return static result

    struct evbuffer *evbuf;
    evbuf = evbuffer_new();
    if (buf == NULL)
    {
        evhttp_send_error(d->req, 500, "Internal Server Error");
        free_req_data(&d);
        fprintf(stderr, "info.c:got_api(): couldn't alloc evbuffer\n");
        return;
    }

    evhttp_remove_header(d->req->output_headers, "content-type");
    evhttp_add_header(d->req->output_headers, "content-type", "application/json");
    evhttp_add_header(d->req->output_headers, "cache-control", "no-cache");
    evbuffer_add_printf(evbuf, "{ \"eventName\": \"%s\", \"description\": \"%s\", \"serverTime\": %d, \"startTime\": %d, \"duration\": %d, \"login\": \"%s\", \"title\": \"%s\", \"profile_image\": \"%s\" }\n", d->event_title, d->description, (int)time(0), (int)(d->start), d->duration, d->login, d->channel_title, d->profile_image);
    evhttp_send_reply(d->req, 200, "OK", evbuf);
    evbuffer_free(evbuf);
    free_req_data(&d);
}
Ejemplo n.º 18
0
int main(int argc, char **argv) {

//	int res = isatty(fileno( stdin));
//
//	if(!res){
//		fprintf(stderr, "Must provide input document on stdin\n");
//		exit(1);
//	}

	XML_Parser p = XML_ParserCreate(NULL);
	if (!p) {
		fprintf(stderr, "Couldn't allocate memory for parser\n");
		exit(-1);
	}




	XML_UseParserAsHandlerArg(p);
	XML_SetElementHandler(p, start_hndl, end_hndl);
	XML_SetCharacterDataHandler(p, char_hndl);
	XML_SetProcessingInstructionHandler(p, proc_hndl);

	/* Notice that the default handler is not set at this point */

	for (;;) {
		int done;
		int len;
		fgets(Buff, sizeof(Buff), stdin);





		len = strlen(Buff);
		if (ferror(stdin)) {
			fprintf(stderr, "Read error\n");
			exit(-1);
		}
		done = feof(stdin);
		if (XML_Parse(p, Buff, len, done) != XML_STATUS_OK) {
			fprintf(stderr, "Parse error at line %lu :\n %s \n",
					XML_GetCurrentLineNumber(p), XML_ErrorString(
							XML_GetErrorCode(p)));
			exit(-1);
		}

		if (done)
			break;
	}
	printf("\n");
	return 0;
} /* End main */
Ejemplo n.º 19
0
//-----------------------------------------------------------------------
void ExpatParser::parseXMLFile(XMLHandler& handler,
                               const Ogre::String& xmlName, const Ogre::String& xmlResourceGroup,
                               const Ogre::String& schemaName, const Ogre::String& schemaResourceGroup)
{
    XML_Parser parser = XML_ParserCreate(NULL);

    try
    {
        MyUserData myUserData;
        myUserData.handler = &handler;
        if (_locale.get())
            myUserData.converter = boost::bind(&expat_to_local, _1, _2, boost::ref(*_locale));
        else
            myUserData.converter = boost::bind(&expat_to_local_win32, _1, _2, boost::ref(_buffer));

        XML_SetUserData(parser, &myUserData);
        XML_SetElementHandler(parser, expatStartElementHandler, expatEndElementHandler);
        XML_SetCharacterDataHandler(parser, expatCharacterDataHandler);

        const size_t MaxBufferSize = 64*1024;
        Ogre::DataStreamPtr dataStream = Ogre::ResourceGroupManager::getSingleton().openResource(xmlName, xmlResourceGroup);
        bool done;
        do
        {
            void* buffer = XML_GetBuffer(parser, MaxBufferSize);
            if (!buffer)
            {
                OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR,
                            "Can't allocate buffer while parse XML file '" + xmlName + "'.",
                            "ExpatParser::parseXMLFile");
            }

            size_t count = dataStream->read(buffer, MaxBufferSize);
            done = dataStream->eof();

            if (XML_ParseBuffer(parser, count, done) != XML_STATUS_OK)
            {
                OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR,
                            "An error occurred while parsing XML file '" + xmlName +
                            "' at line " + Ogre::StringConverter::toString(XML_GetCurrentLineNumber(parser)) +
                            ". Additional information: " + XML_ErrorString(XML_GetErrorCode(parser)),
                            "ExpatParser::parseXMLFile");
            }
        } while (!done);
    }
    catch(...)
    {
        XML_ParserFree(parser);
        throw;
    }

    XML_ParserFree(parser);
}
Ejemplo n.º 20
0
XML_Parser sb_parser_new()
{
    XML_Parser p;
    BrokerParserData *bp = calloc(1, sizeof(BrokerParserData));
    p = XML_ParserCreateNS(NULL, ' ');

    XML_SetUserData(p, bp);
    XML_SetElementHandler(p, sbx_start, sbx_end);
    XML_SetCharacterDataHandler(p, getText);

    return p;
}
Ejemplo n.º 21
0
static void init_parser(XML_Parser parser, expat_parser *parser_data)
{
    XML_SetUserData(parser, parser_data);

    XML_SetStartElementHandler(parser, (XML_StartElementHandler)start_element_handler);
    XML_SetEndElementHandler(parser, (XML_EndElementHandler)end_element_handler);
    XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)character_data_handler);
    XML_SetStartNamespaceDeclHandler(parser, (XML_StartNamespaceDeclHandler)namespace_decl_handler);

    XML_SetReturnNSTriplet(parser, 1);
    XML_SetDefaultHandler(parser, NULL);
};
Ejemplo n.º 22
0
void XmlReader::Open() {
#if defined(READER_SUPPORT_XML)
	stream = fopen(filename.c_str(), "r");
	parser = XML_ParserCreate("UTF-8");

	XML_SetUserData(parser, (void*) this);
	XML_SetElementHandler(parser, StartElementHandler, EndElementHandler);
	XML_SetCharacterDataHandler(parser, CharacterDataHandler);

	handlers.push_back(NULL);
#endif
}
Ejemplo n.º 23
0
/**
 * @function expat.parser
 * 
 * ### Synopsis
 * 
 * var parser = expat.parser(thisObj, startFn, endFn, textFn);
 * 
 * Instantiate an XML parser.
 * 
 * The thisObj argument is the value of "this" passed to startFn and endFn.
 * 
 * The startFn function is called with an element name and attributes object when an open tag is encountered.
 * 
 * The endFn function is called with an element name when a close tag is encountered.
 *
 * The textFn function is called with the value between the tags.
 *
 * ### Callback Signatures
 *
 * startFn(name, attr); // {string} name, {object} attr
 * endFn(name); // {string} name
 * textFn(text); // {string} text
 *
 * @param {object} thisObj - object to be passed as "this" to startFn, endFn, and textFn
 * @param {function} startFn - function to be called when a start tag is encountered during parsing.
 * @param {function} endFn - function to be called when an end tag is encountered during parsing.
 * @param {function} textFn - function to be called with the text (value) between start/end tags during parsing.
 *
 * @return {object} parser - opaque handle to an expat parser.
 */
static JSVAL parser(JSARGS args) {
    p *ptr = new p;
    ptr->thisObj = Persistent<Object>::New(args[0]->ToObject());
    ptr->parser = XML_ParserCreate(NULL);
    XML_SetUserData(ptr->parser, (void *) ptr);
    XML_SetElementHandler(ptr->parser, start, end);
    XML_SetCharacterDataHandler(ptr->parser, charHandler);
    ptr->start = Persistent<Function>::New(Local<Function>::Cast(args[1]));
    ptr->end = Persistent<Function>::New(Local<Function>::Cast(args[2]));
    ptr->charHandler = Persistent<Function>::New(Local<Function>::Cast(args[3]));
    return Opaque::New(ptr);
}
Ejemplo n.º 24
0
//----------------------
///////////////////////////////////////////////////////
//
// ChercheLaTag() -- better to rewrite this!!
//
///////////////////////////////////////////////////////
void simpleXMLparser::CherchezLaTag()
{
  XML_ParserReset(XMLp, NULL);

  XML_SetElementHandler(XMLp, simpleXMLparser::openingHndl, simpleXMLparser::closingHndl);
  XML_SetCharacterDataHandler(XMLp, simpleXMLparser::textHndl);
  XML_SetUserData(XMLp, this);   

  FILE * inputFile;
  if  ( ! (inputFile = fopen(xmlFileName,"r")) )
    {
      std::cout << "Error: File \"" << xmlFileName << "\" does not exist\n" ;
      exit(-1);
    }
	

  searchTag=tXMLpathList.front();     // tag for search
  currentTagNumber=0;                

  Depth = 0;
  prevDepth = 0;
  searchDepth=  tXMLpathList.size(); 

  currentAttr.clear();
  returnAttr.clear();

  ifStop=false;
 
  for (;;) {
    int done;
    int len;
  
    len = fread(Buff, 1, BUFFSIZE, inputFile);
    if (ferror(inputFile)) {
      std::cout << "\nError: read error\n\n";
      exit(-1);
    }
    done = feof(inputFile);

    if (XML_Parse(XMLp, Buff, len, done) == XML_STATUS_ERROR) {
      std::cout << "\nError: parse error at line " 
		<< XML_GetCurrentLineNumber(XMLp) << ": "
		<< XML_ErrorString(XML_GetErrorCode(XMLp)) << "\n\n";
      exit(-1);
    }

    if (done)
      break;
  }

  fclose(inputFile);
  tXMLpathList.clear();
}
Ejemplo n.º 25
0
/**
 * Parse an XML string into a nested list.
 * The second parameter indicates if body text (text within XML tags)
 * should show up among the children of the tag or in its own
 * section.
 *
 * See documentation (ext-xml.README) for examples.
 */
static package 
parse_xml(const char *data, int bool_stream)
  {
  /*
   * FIXME: Feed expat smaller chunks of the string and 
   * check for task timeout between chunks
   *
   */
  int decoded_length;
  const char *decoded;
  package result; 
  XML_Parser parser = XML_ParserCreate(NULL);
  XMLdata *root = new_node(NULL, "");
  XMLdata *child = root;
  
  decoded_length = strlen(data);
  decoded = data;
  XML_SetUserData(parser, &child);
  XML_SetElementHandler(parser, xml_startElement, xml_endElement);
  if(bool_stream) {
    XML_SetCharacterDataHandler(parser, xml_streamCharacterDataHandler);
  } else {
    XML_SetCharacterDataHandler(parser, xml_characterDataHandler);
  }
  if (!XML_Parse(parser, decoded, decoded_length, 1)) {
    Var r;
    r.type = TYPE_INT;
    r.v.num = XML_GetCurrentByteIndex(parser);
    flush_nodes(child);
    result = make_raise_pack(E_INVARG, 
			     XML_ErrorString(XML_GetErrorCode(parser)),
			     r);
  } else {
    finish_node(root);
    result = make_var_pack(var_ref(root->element.v.list[4].v.list[1]));
    free_node(root);
  }
  XML_ParserFree(parser);
  return result; 
}
Ejemplo n.º 26
0
void xmlParseClientEvent (char *xml_string, int len, NOTICE *notice)
{

  XML_Parser parser;
  CLIENT_PARSE_INFO *parse_info;

  parse_info = calloc (1, sizeof *parse_info);

  parser = XML_ParserCreate (NULL);

  if (!parser) {

    logMsg (DBG_GEN, "Couldn't create an XML parsing object: %s\n",
            (char *)XML_ErrorString (XML_GetErrorCode (parser) ));
    free (parse_info);
    return;

  }

  /* Set handlers */
  XML_SetElementHandler (parser, xmlParseClientStart, xmlParseClientEnd);
  XML_SetCharacterDataHandler (parser, xmlParseClientChar);

  /* Set up data structures to pass */
  if (parse_info) {
    parse_info->notice = notice;
    parse_info->parser = parser;
    parse_info->current_tag = NULL;
  }

  XML_SetUserData (parser, parse_info);

  /* Now parse our xml string buffer. Note that we supply a final arguement
   * of 1 which tells the parser that this is the last bit of xml data that
   * it's going to parse, which is true for this instantation
   */
  if (! XML_Parse (parser, xml_string, len, 1) ) {

    logMsg (DBG_GEN, "Uh Oh! There was an XML parsing error: %s\n",
            (char *)XML_ErrorString ( XML_GetErrorCode (parser) ));
    /* Try to continue */

  }

  XML_ParserFree (parser);

  if (parse_info && parse_info->current_tag) {
    free (parse_info->current_tag);
  }
  free (parse_info);

}
Ejemplo n.º 27
0
void opml_process(gchar *path, OPMLProcessFunc function, gpointer data)
{
	OPMLProcessCtx *ctx = NULL;
	gchar *contents = NULL;
	GError *error = NULL;
	gint status, err;

	/* Initialize our context */
	ctx = malloc( sizeof(OPMLProcessCtx) );
	ctx->parser = XML_ParserCreate(NULL);
	ctx->depth = 0;
	ctx->str = NULL;
	ctx->user_function = function;
	ctx->body_reached = FALSE;
	ctx->user_data = data;

	/* Set expat parser handlers */
	XML_SetUserData(ctx->parser, (void *)ctx);
	XML_SetElementHandler(ctx->parser,
			_opml_parser_start,
			_opml_parser_end);
	XML_SetCharacterDataHandler(ctx->parser, libfeed_expat_chparse);
	XML_SetUnknownEncodingHandler(ctx->parser,
			feed_parser_unknown_encoding_handler, NULL);

	g_file_get_contents(path, &contents, NULL, &error);

	if( error || !contents )
		return;

/*
	lines = g_strsplit(contents, '\n', 0);

	while( lines[i] ) {
		status = XML_Parse(ctx->parser, lines[i], strlen(lines[i]), FALSE);
		if( status == XML_STATUS_ERROR ) {
			err = XML_GetErrorCode(ctx->parser);
			sprintf(stderr, "\nExpat: --- %s\n\n", XML_ErrorString(err));
		}
	}
*/

	status = XML_Parse(ctx->parser, contents, strlen(contents), FALSE);
	err = XML_GetErrorCode(ctx->parser);
	fprintf(stderr, "\nExpat: --- %s (%s)\n\n", XML_ErrorString(err),
			(status == XML_STATUS_OK ? "OK" : "NOT OK"));

	XML_Parse(ctx->parser, "", 0, TRUE);

	XML_ParserFree(ctx->parser);
	g_free(ctx);
}
Ejemplo n.º 28
0
JSBool
xmljs_parse(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    XMLCallback *cb;
    XML_Parser xml;
    JSString *str;
    JSBool ok;

    cb = (XMLCallback *)JS_GetPrivate(cx, obj);
    if (!cb) {
	JS_ReportError(cx, "XMLParser object has no parser!");
	return JS_FALSE;
    }
    if (cb->preParse &&
	!cb->preParse(cx, obj, argc, argv, rval))
	return JS_FALSE;
    if (argc < 1) {
	*rval = JSVAL_TRUE;
	return JS_TRUE;
    }

    xml = XML_ParserCreate(NULL);
    if (!xml)
	return JS_FALSE;	/* XXX report error */
    /* after this point, have to leave via out: */

    XML_SetElementHandler(xml, cb->start, cb->end);
    XML_SetCharacterDataHandler(xml, cb->cdata);
    XML_SetProcessingInstructionHandler(xml, cb->processing);
    XML_SetUserData(xml, (void *)cb);
    cb->xml = xml;
    str = JS_ValueToString(cx, argv[0]);
    if (!XML_Parse(xml, JS_GetStringBytes(str), JS_GetStringLength(str), 1)) {
	str = JS_NewStringCopyZ(cx, XML_ErrorString(XML_GetErrorCode(xml)));
	if (!str) {
	    ok = JS_FALSE;
	    goto out;
	}
	if (!JS_DefineProperty(cx, obj, "error", STRING_TO_JSVAL(str),
			       NULL, NULL, JSPROP_ENUMERATE)) {
	    ok = JS_FALSE;
	    goto out;
	}
	*rval = JSVAL_FALSE;
    } else {
	*rval = JSVAL_TRUE;
    }
 out:
    XML_ParserFree(xml);
    cb->xml = NULL;
    return ok;
}
Ejemplo n.º 29
0
int
repo_add_appdata(Repo *repo, FILE *fp, int flags)
{
  Pool *pool = repo->pool;
  struct parsedata pd;
  struct stateswitch *sw;
  Repodata *data;
  char buf[BUFF_SIZE];
  int i, l;
  int ret = 0;

  data = repo_add_repodata(repo, flags);
  memset(&pd, 0, sizeof(pd));
  pd.repo = repo;
  pd.pool = repo->pool;
  pd.data = data;

  pd.content = malloc(256);
  pd.acontent = 256;

  for (i = 0, sw = stateswitches; sw->from != NUMSTATES; i++, sw++)
    {
      if (!pd.swtab[sw->from])
        pd.swtab[sw->from] = sw;
      pd.sbtab[sw->to] = sw->from;
    }

  XML_Parser parser = XML_ParserCreate(NULL);
  XML_SetUserData(parser, &pd);
  XML_SetElementHandler(parser, startElement, endElement);
  XML_SetCharacterDataHandler(parser, characterData);

  for (;;)
    {
      l = fread(buf, 1, sizeof(buf), fp);
      if (XML_Parse(parser, buf, l, l == 0) == XML_STATUS_ERROR)
	{
          pool_error(pool, -1, "repo_appdata: %s at line %u:%u\n", XML_ErrorString(XML_GetErrorCode(parser)), (unsigned int)XML_GetCurrentLineNumber(parser), (unsigned int)XML_GetCurrentColumnNumber(parser));
	  ret = -1;
	  break;
	}
      if (l == 0)
	break;
    }
  XML_ParserFree(parser);

  if (!(flags & REPO_NO_INTERNALIZE))
    repodata_internalize(data);

  free(pd.content);
  return ret;
}
Ejemplo n.º 30
0
static void
_run_character_check(XML_Char *text, XML_Char *expected,
                     const char *file, int line)
{
    CharData storage;

    CharData_Init(&storage);
    XML_SetUserData(parser, &storage);
    XML_SetCharacterDataHandler(parser, accumulate_characters);
    if (XML_Parse(parser, text, strlen(text), XML_TRUE) == XML_STATUS_ERROR)
        _xml_failure(parser, file, line);
    CharData_CheckXMLChars(&storage, expected);
}