Example #1
0
xmlParserCtxtPtr
RS_XML_xmlCreateConnectionParserCtxt(USER_OBJECT_ con)
{
      xmlParserInputBufferPtr buf;
      xmlParserCtxtPtr ctx = NULL;

#ifdef LIBXML2
      ctx = xmlNewParserCtxt();
#ifndef LIBXML2_NEW_BUFFER  // < 2.9.1
      ctx->_private = (USER_OBJECT_) con;
                                      /* R_chk_calloc */
      buf = (xmlParserInputBufferPtr) calloc(1, sizeof(xmlParserInputBuffer));
      buf->readcallback = RS_XML_readConnectionInput;
      buf->context = (void*) ctx;
      buf->raw = NULL; /* buf->buffer; */
      xmlBufferPtr tmp = xmlBufferCreate();
      buf->buffer = tmp;
#else
    RFunCtxData *userData = (RFunCtxData *) R_alloc(sizeof(RFunCtxData), 1);
    userData->fun = con;
    userData->ctx = ctx;
    buf = xmlParserInputBufferCreateIO(RS_XML_readConnectionInput, NULL, userData, XML_CHAR_ENCODING_NONE);
#endif

      xmlParserInputPtr input = xmlNewIOInputStream(ctx, buf, XML_CHAR_ENCODING_NONE);
      if(!input) {
	  PROBLEM "can't create new IOInputStream"
	      ERROR;
      }
      inputPush(ctx, input);
#endif
      return(ctx);
}
/* call-seq:
 *    XML::Parser::Context.io(io) -> XML::Parser::Context
 *
 * Creates a new parser context based on the specified io object.
 *
 * Parameters:
 *
 *  io - A ruby IO object.
*/
static VALUE rxml_parser_context_io(VALUE klass, VALUE io)
{
  xmlParserCtxtPtr ctxt;
  xmlParserInputBufferPtr input;
  xmlParserInputPtr stream;

  input = xmlParserInputBufferCreateIO((xmlInputReadCallback) rxml_read_callback, NULL,
                                       (void*)io, XML_CHAR_ENCODING_NONE);
    
  ctxt = xmlNewParserCtxt();
  if (!ctxt)
  {
    xmlFreeParserInputBuffer(input);
    rxml_raise(&xmlLastError);
  }

  stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);

  if (!stream)
  {
    xmlFreeParserInputBuffer(input);
    xmlFreeParserCtxt(ctxt);
    rxml_raise(&xmlLastError);
  }
  inputPush(ctxt, stream);
  return rxml_parser_context_wrap(ctxt);
}
Example #3
0
bool CSpmXml::LoadXML(const QString& strXML, bool bDTDValidation)
{
	xmlParserCtxtPtr pXMLParser = xmlNewParserCtxt();
	if (0 == pXMLParser)
		return false;

	int nOptions = XML_PARSE_NOBLANKS;
	if (bDTDValidation)
		nOptions |= XML_PARSE_DTDVALID;

	m_pXMLDoc = xmlCtxtReadDoc(pXMLParser, (xmlChar*)strXML.toUtf8().data(), "", NULL, nOptions);

	if (0 == m_pXMLDoc)
	{
		xmlFreeParserCtxt(pXMLParser);
		return false;
	}

	// Проверка корректности структуры
	if (bDTDValidation && (false == pXMLParser->valid))
	{
		xmlFreeParserCtxt(pXMLParser);
		return false;
	}

	m_pCurNode = xmlDocGetRootElement(m_pXMLDoc);
	if (0 == m_pCurNode)
		return false;

	SetModified(false);
	xmlFreeParserCtxt(pXMLParser);
	return true;
}
Example #4
0
bool XMLReader::isValid(const QString &_inFile)
{
    LIBXML_TEST_VERSION
    //reset the generic error handler
    initGenericErrorDefaultFunc(NULL);
    QString ErrorString;
    //supply custom error handler
    xmlSetStructuredErrorFunc(&ErrorString, XMLReader::xmlErrorHandler);

    xmlParserCtxtPtr Context; /* the parser context */
    xmlDocPtr Doc; /* the resulting document tree */

    /* create a parser context */
    Context = xmlNewParserCtxt();
    if (Context == NULL)
      throw exInvalidXML("Failed to allocate parser context");

    QFile File(_inFile);
    File.open(QIODevice::ReadOnly);
    int FD = File.handle();

    /* parse the file, activating the DTD validation option */
    Doc = xmlCtxtReadFd(Context, FD, ".", NULL, XML_PARSE_DTDVALID);

    /* check if parsing suceeded */
    if (Doc == NULL)
        throw exInvalidXML("Unable to read XML Buffer");
    else
      xmlFreeDoc(Doc);
    /* free up the parser context */
    xmlFreeParserCtxt(Context);

    return true;
}
Example #5
0
static void
xml_tree_model_init (xmlTreeModel *model)
{
	xmlSetStructuredErrorFunc(model, throw_xml_error);
	xsltSetGenericErrorFunc(model, throw_xsl_error);
	
	model->n_columns       = XML_TREE_MODEL_N_COLUMNS;
	model->column_types[0] = G_TYPE_INT;	/* XML_TREE_MODEL_COL_TYPE	*/
	model->column_types[1] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_NS	*/
	model->column_types[2] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_NAME	*/
	model->column_types[3] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_CONTENT	*/
	model->column_types[4] = G_TYPE_INT;		/* XML_TREE_MODEL_COL_LINE	*/
	model->column_types[5] = G_TYPE_ULONG;		/* XML_TREE_MODEL_COL_POS	*/
	model->column_types[6] = G_TYPE_STRING;	/* XML_TREE_MODEL_COL_PATH	*/
	g_assert (XML_TREE_MODEL_N_COLUMNS == 7);
 
	model->stamp = g_random_int();  /* Random int to check whether an iter belongs to our model */
	model->xmldoc = NULL;
	model->xsldoc = NULL;
	model->xpath = NULL;
	model->valid = FALSE;
	
	model->parser = xmlNewParserCtxt();
	model->nodeinfo = NULL;
	model->offset = 0;
}
Example #6
0
File: Vpz.cpp Project: SJasson/vle
void Vpz::validateFile(const std::string& filename)
{
    xmlParserCtxtPtr ctxt;
    xmlDocPtr doc;

    ctxt = xmlNewParserCtxt();
    if (ctxt == NULL) {
        throw utils::SaxParserError(_("Failed to allocate parser context\n"));
    }

    doc = xmlCtxtReadFile(ctxt, filename.c_str(), NULL, XML_PARSE_DTDVALID);
    if (not doc) {
        std::string msg((fmt(_("Failed to parse '%1%': %2%")) % filename %
                         (ctxt->lastError.message ? ctxt->lastError.message :
                          "")).str());

        xmlFreeParserCtxt(ctxt);

        throw utils::SaxParserError(msg);
    }

    if (ctxt->valid == 0) {
        std::string msg((fmt(_("Failed to validate '%1%': %2%")) % filename %
                         (ctxt->lastError.message ? ctxt->lastError.message :
                          "")).str());

        xmlFreeDoc(doc);
        xmlFreeParserCtxt(ctxt);

        throw utils::SaxParserError(msg);
    }
    xmlFreeParserCtxt(ctxt);
}
Example #7
0
bool MainWindow::OpenXMLDocument(const QString &file_name) {
  FreeXMLDocument();

  xmlParserCtxtPtr parser = xmlNewParserCtxt();
  if (0 == parser)
    return false;

  xml_doc_ptr_ = xmlCtxtReadFile(parser,
                                 file_name.toLocal8Bit().data(),
                                 NULL,
                                 XML_PARSE_NOBLANKS);// | XML_PARSE_DTDVALID);
  if (false == parser->valid) {
    QMessageBox::critical(this, tr("Открытие XML документа"),
                          tr("Структура файла %1 не соответствует "
                          "DTD-диаграмме").arg(file_name),
                          QMessageBox::Ok);
    SetCurrentFileName("", false);
    xmlFreeParserCtxt(parser);
    FreeXMLDocument();
    return false;
  }
  AddItem(xmlDocGetRootElement(xml_doc_ptr_));
  xmlFreeParserCtxt(parser);
  UpdateButtons();
  return true;
}
Example #8
0
dpl_status_t
dpl_s3_parse_list_bucket(const dpl_ctx_t *ctx,
                         const char *buf,
                         int len,
                         dpl_vec_t *objects,
                         dpl_vec_t *common_prefixes)
{
  xmlParserCtxtPtr ctxt = NULL;
  xmlDocPtr doc = NULL;
  int ret;
  xmlNode *tmp;
  //ssize_t cc;

  //cc = write(1, buf, len);

  if ((ctxt = xmlNewParserCtxt()) == NULL)
    {
      ret = DPL_FAILURE;
      goto end;
    }

  doc = xmlCtxtReadMemory(ctxt, buf, len, NULL, NULL, 0u);
  if (NULL == doc)
    {
      ret = DPL_FAILURE;
      goto end;
    }

  for (tmp = xmlDocGetRootElement(doc); NULL != tmp; tmp = tmp->next)
    {
      if (tmp->type == XML_ELEMENT_NODE)
        {
          DPRINTF("name: %s\n", tmp->name);

          if (!strcmp((char *) tmp->name, "ListBucketResult"))
            {
              ret = parse_list_bucket_children(tmp->children, objects, common_prefixes);
              if (DPL_SUCCESS != ret)
                return DPL_FAILURE;
            }
        }
      else if (tmp->type == XML_TEXT_NODE)
        {
          DPRINTF("content: %s\n", tmp->content);
        }
    }

  ret = DPL_SUCCESS;

 end:

  if (NULL != doc)
    xmlFreeDoc(doc);

  if (NULL != ctxt)
    xmlFreeParserCtxt(ctxt);

  return ret;
}
Example #9
0
  /* Taken from libxml2, xmlSAXParseMemoryWithData */
xmlDocPtr mxslt_doc_xml_load_entity(mxslt_doc_t * document, char * localfile) {
  xmlParserCtxtPtr ctx;
  xmlParserInputPtr input;
  xmlDocPtr retval;
  xmlChar * filename;

  mxslt_doc_debug_print(document, MXSLT_DBG_LIBXML | MXSLT_DBG_DEBUG | MXSLT_DBG_VERBOSE0,
		"load_entity/xmlCreateMemoryParserCtxt -- replacing entities: %08x\n", xmlSubstituteEntitiesDefaultValue);

    /* SNIPPET: This is a good mix&shake of 
     * xmlCreateMemoryParserCtxt, xmlCreateFileParserCtxt */
  ctx=xmlNewParserCtxt();
  if(ctx == NULL)
    return NULL;

#if LIBXML_VERSION >= 20600
  xmlCtxtUseOptions(ctx, MXSLT_XSLT_OPTIONS);
#endif

    /* Remember which document we are parsing
     * in this context */
  /* ctx->_private=document; */

  filename=xmlCanonicPath((xmlChar *)localfile);
  if(filename == NULL) {
    xmlFreeParserCtxt(ctx);
    return NULL;
  }
  
  input=xmlLoadExternalEntity((char *)filename, NULL, ctx);
  xmlFree(filename);
  if(input == NULL) {
    xmlFreeParserCtxt(ctx);
    return NULL;
  }

  inputPush(ctx, input);

  if(ctx->directory == NULL)
    ctx->directory=xmlParserGetDirectory(localfile);
    /* END SNIPPET */

  /* MXSLT_DUMP_CTX(ctx); */

    /* Parse document */
  xmlParseDocument(ctx);

  if(ctx->wellFormed)
    retval=ctx->myDoc;
  else {
    retval=NULL;
    xmlFreeDoc(ctx->myDoc);
    ctx->myDoc=NULL;
  }
  xmlFreeParserCtxt(ctx);

  return retval;
}
Example #10
0
/*
 * The hierarchical place tree for a shared memory system is specified as an XML
 * file containing the hierarchy of memory spaces it contains. In general, this
 * hierarchy is multi-layered and may include a separate layer for system
 * memory, L3 caches, L2 caches, L1 caches, etc.
 *
 * Each layer is described by two properties: a type and a count/num. For
 * example, the type may be "mem" whose contents are explicitly managed by the
 * programmer, or a "cache" whose contents are automatically managed. The count
 * refers to the fan-out at a given level. For example, a machine with main
 * memory feeding to two sockets each with their own L3 cache would have a count
 * of 2 for the L3 layer.
 *
 * An example HPT specification is below. This specification describes a machine
 * with a single system memory, two L3 caches, each of which fans out to 6 L1/L2
 * caches.
 *
 * <HPT version="0.1" info="2 hex core2 Intel Westmere processors">
 *   <place num="1" type="mem">
 *     <place num="2" type="cache"> <!-- 2 sockets with common L3 in each -->
 *       <place num="6" type="cache"> <!-- 6 L2/L1 cache per socket -->
 *         <worker num="1"/>
 *       </place>
 *     </place>
 *   </place>
 * </HPT>
 *
 * While homogeneous systems will usually have this singly-nested structure, a
 * machine with multiple types of memory sitting below system memory may have
 * multiple elements at the same nesting level, e.g. both L3 and GPU device
 * memory at the same level in the hierarchy.
 *
 * read_hpt parses one of these XML files and produces the equivalent place
 * hierarchy, returning the root of that hierarchy. The schema of the HPT XML
 * file is stored in $HCLIB_HOME/hpt/hpt.dtd.
 */
place_t *read_hpt(place_t *** all_places, int *num_pl, int *nproc,
                  hclib_worker_state *** all_workers, int *num_wk) {
    const char *filename = getenv("HCLIB_HPT_FILE");
    place_t *hpt;
    if (filename == NULL) {
        const char *workers_str = getenv("HCLIB_WORKERS");
        uint32_t num_workers;
        if (workers_str) {
            num_workers = atoi(workers_str);
        } else {
            num_workers = sysconf(_SC_NPROCESSORS_ONLN);
            fprintf(stderr, "WARNING: HCLIB_WORKERS not provided, running with "
                    "default of %u\n", num_workers);
        }

        hpt = generate_fake_hpt(num_workers, all_places, num_pl, nproc,
                                all_workers, num_wk);
    } else {
        /* create a parser context */
        xmlParserCtxt *ctxt = xmlNewParserCtxt();
        if (ctxt == NULL) {
            fprintf(stderr, "Failed to allocate parser context\n");
            return NULL;
        }
        /* parse the file, activating the DTD validation option */
        xmlDoc *doc = xmlCtxtReadFile(ctxt, filename, NULL, XML_PARSE_DTDVALID);
        /* check if parsing succeeded */
        if (doc == NULL) {
            fprintf(stderr, "Failed to parse %s\n", filename);
            return NULL;
        }

        /* check if validation suceeded */
        if (ctxt->valid == 0) {
            fprintf(stderr, "Failed to validate %s\n", filename);
            return NULL;
        }

        xmlNode *root_element = xmlDocGetRootElement(doc);

        hpt = parseHPTDoc(root_element);

        /*free the document */
        xmlFreeDoc(doc);

        /* free up the parser context */
        xmlFreeParserCtxt(ctxt);
    }

    /*
     * This takes places which have num > 1 and workers that have num > 1 and
     * fully expand them in the place tree so that every node in the tree
     * corresponds to a single place/worker.
     */
    unrollHPT(hpt, all_places, num_pl, nproc, all_workers, num_wk);

    return hpt;
}
Example #11
0
static dpl_status_t
_multipart_parse_init(const dpl_ctx_t *ctx,
                      const char *buf, int len,
                      const char **uploadidp)
{
    dpl_status_t          ret = DPL_SUCCESS;
    xmlParserCtxtPtr      ctxt;
    xmlDocPtr             doc;
    xmlNode               *elem;

    ctxt = xmlNewParserCtxt();
    if (ctxt == NULL)
        return DPL_FAILURE;

    doc = xmlCtxtReadMemory(ctxt, buf, len, NULL, NULL, 0u);
    if (doc == NULL) {
        xmlFreeParserCtxt(ctxt);
        return DPL_FAILURE;
    }

    elem = xmlDocGetRootElement(doc);
    while (elem != NULL)
    {
        if (elem->type == XML_ELEMENT_NODE)
        {
            if (!strcmp((char *) elem->name, "InitiateMultipartUploadResult"))
            {
                elem = elem->children;
                ret = DPL_FAILURE;
                while (elem != NULL)
                {
                    if (elem->type == XML_ELEMENT_NODE)
                    {
                        if (!strcmp((char *) elem->name, "UploadId"))
                        {
                            ret = DPL_SUCCESS;
                            *uploadidp = strdup((char *) elem->children->content);
                            if (NULL == *uploadidp)
                                ret = DPL_ENOMEM;
                            break;
                        }
                    }
                    elem = elem->next;
                }
                // Reaching here means that we already browsed
                // the InitiateMultipartUploadResult xml subtree,
                // whether we found UploadId or not.
                break;
            }
        }
        elem = elem->next;
    }

    xmlFreeDoc(doc);
    xmlFreeParserCtxt(ctxt);

    return ret;
}
Example #12
0
/*< private >*/
static gboolean
lt_xml_read_subtag_registry(lt_xml_t  *xml,
			    GError   **error)
{
	gchar *regfile = NULL;
	xmlParserCtxtPtr xmlparser;
	xmlDocPtr doc = NULL;
	GError *err = NULL;

	g_return_val_if_fail (xml != NULL, FALSE);

#ifdef GNOME_ENABLE_DEBUG
	regfile = g_build_filename(BUILDDIR, "data", "language-subtag-registry.xml", NULL);
	if (!g_file_test(regfile, G_FILE_TEST_EXISTS)) {
		g_free(regfile);
#endif
	regfile = g_build_filename(lt_db_get_datadir(), "language-subtag-registry.xml", NULL);
#ifdef GNOME_ENABLE_DEBUG
	}
#endif
	xmlparser = xmlNewParserCtxt();
	if (!xmlparser) {
		g_set_error(&err, LT_ERROR, LT_ERR_OOM,
			    "Unable to create an instance of xmlParserCtxt.");
		goto bail;
	}
	doc = xmlCtxtReadFile(xmlparser, regfile, "UTF-8", 0);
	if (!doc) {
		g_set_error(&err, LT_ERROR, LT_ERR_FAIL_ON_XML,
			    "Unable to read the xml file: %s",
			    regfile);
		goto bail;
	}
	xml->subtag_registry = doc;
	lt_mem_add_ref(&xml->parent, xml->subtag_registry,
		       (lt_destroy_func_t)xmlFreeDoc);

  bail:
	g_free(regfile);
	if (xmlparser)
		xmlFreeParserCtxt(xmlparser);

	xmlCleanupParser();

	if (err) {
		if (error)
			*error = g_error_copy(err);
		else
			g_warning(err->message);
		g_error_free(err);

		return FALSE;
	}

	return TRUE;
}
Example #13
0
void Editor_Export::load (string html)
{
  // The web editor may insert non-breaking spaces. Convert them to normal ones.
  html = filter_string_str_replace ("&nbsp;", " ", html);
  
  // The web editor produces <hr> following the HTML specs, but Bibledit needs
  // <hr/> for its XML parser.
  html = filter_string_str_replace ("<hr>", "<hr/>", html);
  
  // The user may add several spaces in sequence. Convert them to single spaces.
  html = filter_string_str_replace ("   ", " ", html);
  html = filter_string_str_replace ("  ", " ", html);
  
  // DOMDocument deals well with imperfect markup, but it may throw warnings to the default error handler.
  // Therefore keep the errors separate.
  xmlGenericErrorFunc handler = (xmlGenericErrorFunc) error_handler;
  initGenericErrorDefaultFunc (&handler);
  
  // To help loadHTML() process utf8 correctly, set the correct meta tag before any other text.
  /*
  string prefix =
  "<!DOCTYPE html>\n"
  "<html>\n"
  "<head>\n"
  "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n"
  "</head>\n"
  "<body>\n";
  string suffix =
  "\n"
  "</body>\n"
  "</html>\n";
  string xml = prefix + html + suffix;
  htmlParserCtxtPtr context = htmlNewParserCtxt();
  document = htmlCtxtReadMemory (context, xml.c_str(), xml.length(), "", "UTF-8", HTML_PARSE_RECOVER);
  htmlFreeParserCtxt (context);
   */

  // On Android, the HTML parser fails. It returns a NULL document.
  // Therefore use the XML parser instead of the HTML one.
  string prefix =
  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  "<html>\n"
  "<head>\n"
  "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"></meta>\n"
  "</head>\n"
  "<body>\n";
  string suffix =
  "\n"
  "</body>\n"
  "</html>\n";
  string xml = prefix + html + suffix;
  xmlParserCtxtPtr context = xmlNewParserCtxt();
  document = xmlCtxtReadMemory (context, xml.c_str(), xml.length(), "", "UTF-8", XML_PARSE_RECOVER);
  xmlFreeParserCtxt (context);
}
Example #14
0
void parse_config()
{
	FILE *f = NULL;

	fprintf(stderr,"Reading configuration file: \"%s\" ...\n",config_path);
	
	if( (f=fopen (config_path, "r")) == NULL )
	{
		perror("fopen");
		exit(1);
	}

	LIBXML_TEST_VERSION;

	/* create a parser context */
	ctxt = xmlNewParserCtxt();
	if (ctxt == NULL)
	{
		fprintf(stderr, "Failed to allocate parser context\n");
		fclose(f);
		return;
	}
	/* parse the file, activating the DTD validation option */
	doc = xmlCtxtReadFile(ctxt, config_path, NULL, XML_PARSE_DTDVALID);
	/* check if parsing suceeded */
	if (doc == NULL)
	{
		fprintf(stderr, "Failed to parse %s\n", config_path);
	}
	else
	{
		/* check if validation suceeded */
		if (ctxt->valid == 0)
			fprintf(stderr, "Failed to validate %s\n", config_path);
		/* free up the resulting document */
		else
		{
			xmlXPathInit();
			xpctxt= xmlXPathNewContext(doc);
		}
	}

	autoconf();
	get_mail();
	init_syslog();
	parse_routers();
	parse_actions();
#ifdef _COUNTERMEASURES_
        parse_countermeasures();
#endif
	free_xml();
	fclose(f);
	fprintf(stderr,"    Done.\n");
}
Example #15
0
static void
log4g_dom_configurator_init(Log4gDOMConfigurator *self)
{
	self->priv = ASSIGN_PRIVATE(self);
	struct Private *priv = GET_PRIVATE(self);
	priv->ctx = xmlNewParserCtxt();
	priv->appenders = g_hash_table_new_full(g_str_hash, g_str_equal,
				xmlFree, g_object_unref);
	priv->objects = g_hash_table_new_full(g_str_hash, g_str_equal,
				xmlFree, g_object_unref);
}
Example #16
0
static void testCharRanges(void) {
    char data[5];
    xmlParserCtxtPtr ctxt;
    xmlParserInputBufferPtr buf;
    xmlParserInputPtr input;

    memset(data, 0, 5);

    /*
     * Set up a parsing context using the above data buffer as
     * the current input source.
     */
    ctxt = xmlNewParserCtxt();
    if (ctxt == NULL) {
        fprintf(stderr, "Failed to allocate parser context\n");
	return;
    }
    buf = xmlParserInputBufferCreateStatic(data, sizeof(data),
                                           XML_CHAR_ENCODING_NONE);
    if (buf == NULL) {
        fprintf(stderr, "Failed to allocate input buffer\n");
	goto error;
    }
    input = xmlNewInputStream(ctxt);
    if (input == NULL) {
        xmlFreeParserInputBuffer(buf);
	goto error;
    }
    input->filename = NULL;
    input->buf = buf;
    input->cur =
    input->base = xmlBufContent(input->buf->buffer);
    input->end = input->base + 4;
    inputPush(ctxt, input);

    printf("testing char range: 1");
    fflush(stdout);
    testCharRangeByte1(ctxt, data);
    printf(" 2");
    fflush(stdout);
    testCharRangeByte2(ctxt, data);
    printf(" 3");
    fflush(stdout);
    testCharRangeByte3(ctxt, data);
    printf(" 4");
    fflush(stdout);
    testCharRangeByte4(ctxt, data);
    printf(" done\n");
    fflush(stdout);

error:
    xmlFreeParserCtxt(ctxt);
}
Example #17
0
xmlDocPtr
content_to_xml (const gchar *contents, gsize size)
{
	xmlParserCtxtPtr ctxt;
	xmlDocPtr doc;

	ctxt = xmlNewParserCtxt ();
	ctxt->sax->getEntity = xml_process_entities;
	doc = xmlSAXParseMemory (ctxt->sax, contents, size, 1);
	xmlFreeParserCtxt (ctxt);

	return doc;
}
Example #18
0
 libxml2_loader(const char *encoding = NULL, int options = DEFAULT_OPTIONS, const char *url = NULL) :
     ctx_(0),
     encoding_(encoding),
     options_(options),
     url_(url)
 {
     LIBXML_TEST_VERSION;
     ctx_ = xmlNewParserCtxt();
     if (!ctx_)
     {
         throw std::runtime_error("Failed to create parser context.");
     }
 }
Example #19
0
static bool
is_dtd_valid(FILE *input, const char *filename)
{
	bool rc = true;
#if HAVE_LIBXML
	xmlParserCtxtPtr ctx = NULL;
	xmlDocPtr doc = NULL;
	xmlDtdPtr dtd = NULL;
	xmlValidCtxtPtr	dtdctx;
	xmlParserInputBufferPtr	buffer;
	int fd = fileno(input);

	dtdctx = xmlNewValidCtxt();
	ctx = xmlNewParserCtxt();
	if (!ctx || !dtdctx)
		abort();

	buffer = xmlParserInputBufferCreateMem(&DTD_DATA_begin,
					       DTD_DATA_len,
					       XML_CHAR_ENCODING_UTF8);
	if (!buffer) {
		fprintf(stderr, "Failed to init buffer for DTD.\n");
		abort();
	}

	dtd = xmlIOParseDTD(NULL, buffer, XML_CHAR_ENCODING_UTF8);
	if (!dtd) {
		fprintf(stderr, "Failed to parse DTD.\n");
		abort();
	}

	doc = xmlCtxtReadFd(ctx, fd, filename, NULL, 0);
	if (!doc) {
		fprintf(stderr, "Failed to read XML\n");
		abort();
	}

	rc = xmlValidateDtd(dtdctx, doc, dtd);
	xmlFreeDoc(doc);
	xmlFreeParserCtxt(ctx);
	xmlFreeDtd(dtd);
	xmlFreeValidCtxt(dtdctx);
	/* xmlIOParseDTD consumes buffer */

	if (lseek(fd, 0, SEEK_SET) != 0) {
		fprintf(stderr, "Failed to reset fd, output would be garbage.\n");
		abort();
	}
#endif
	return rc;
}
Example #20
0
PKI_CONFIG * PKI_CONFIG_load(char *urlPath)
{
	FILE *file = NULL;
	PKI_CONFIG *doc = NULL;
	URL *url = NULL;
	xmlParserCtxt *parserCtxt = NULL;

	LIBXML_TEST_VERSION

	if (urlPath) url = URL_new( urlPath );
  else return ( NULL );

	// Let's check the URL was parsed correctly
	if( !url || !url->addr ) return(PKI_ERR);

	if ((file = fopen(url->addr, "r")) == NULL)
	{
		URL_free(url);
		return PKI_ERR;
	}
	fclose(file);

	if ((parserCtxt = xmlNewParserCtxt()) == NULL )
	{
		URL_free( url );
		return(PKI_ERR);
	}

#if LIBXML_VERSION > LIBXML_MIN_VERSION
	xmlSetStructuredErrorFunc( parserCtxt, logXmlMessages );
#endif

	/* Do not Keep Blank Nodes */
	xmlKeepBlanksDefault(0);

	/*parse the file and get the DOM */
#if LIBXML_VERSION > LIBXML_MIN_VERSION
	doc = (PKI_CONFIG *) xmlCtxtReadFile(parserCtxt, url->addr, NULL, 
				XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING | 
				XML_PARSE_NOENT );
#else
	doc = (PKI_CONFIG *) xmlCtxtReadFile(parserCtxt, url->addr, NULL, 0);
#endif

	// xmlClearParserCtxt ( parserCtxt );
	xmlFreeParserCtxt ( parserCtxt );
	URL_free(url);

	return( doc );
}
Example #21
0
static void stats_set_entity_decode (long handle, const char *name, const char *value)
{
    xmlParserCtxtPtr parser = xmlNewParserCtxt();
    if (parser)
    {
        xmlChar *decoded = xmlStringDecodeEntities (parser,
                (const xmlChar *) value, XML_SUBSTITUTE_BOTH, 0, 0, 0);
        stats_set (handle, name, (void*)decoded);
        xmlFreeParserCtxt (parser);
        xmlFree (decoded);
        return;
    }
    stats_set (handle, name, value);
}
static gboolean
chatroom_manager_file_parse (EmpathyChatroomManager *manager,
    const gchar *filename)
{
  EmpathyChatroomManagerPriv *priv;
  xmlParserCtxtPtr ctxt;
  xmlDocPtr doc;
  xmlNodePtr chatrooms;
  xmlNodePtr node;

  priv = GET_PRIV (manager);

  DEBUG ("Attempting to parse file:'%s'...", filename);

  ctxt = xmlNewParserCtxt ();

  /* Parse and validate the file. */
  doc = xmlCtxtReadFile (ctxt, filename, NULL, 0);
  if (doc == NULL)
    {
      g_warning ("Failed to parse file:'%s'", filename);
      xmlFreeParserCtxt (ctxt);
      return FALSE;
    }

  if (!empathy_xml_validate (doc, CHATROOMS_DTD_FILENAME))
    {
      g_warning ("Failed to validate file:'%s'", filename);
      xmlFreeDoc (doc);
      xmlFreeParserCtxt (ctxt);
      return FALSE;
    }

  /* The root node, chatrooms. */
  chatrooms = xmlDocGetRootElement (doc);

  for (node = chatrooms->children; node; node = node->next)
    {
      if (strcmp ((gchar *) node->name, "chatroom") == 0)
        chatroom_manager_parse_chatroom (manager, node);
    }

  DEBUG ("Parsed %d chatrooms", g_list_length (priv->chatrooms));

  xmlFreeDoc (doc);
  xmlFreeParserCtxt (ctxt);

  return TRUE;
}
Example #23
0
rss_file *rss_open_file(const char *filename)
{
  xmlParserCtxtPtr ctxt;
  xmlDocPtr doc;
  rss_file *f;
  xmlNode *root_element = NULL;
  gchar *fetched_time;

  ctxt = xmlNewParserCtxt();
  ctxt->sax->getEntity = _get_entity;
  doc = xmlSAXParseFile(ctxt->sax, filename, 0);

  if (!doc) {
    fprintf(stderr, "Error parsing RSS file %s.\n", filename);
    xmlFreeParserCtxt(ctxt);

    return NULL;
  }

  root_element = xmlDocGetRootElement(doc);

  if (!root_element)  {
    xmlFreeDoc(doc);
    xmlFreeParserCtxt(ctxt);

    fprintf(stderr, "Error parsing RSS file %s.\n", filename);
    return NULL;
  }

  /* Establish the time the RSS file was 'fetched'. */
  fetched_time = get_rfc822_time();

  if (!fetched_time) {
    xmlFreeDoc(doc);
    xmlFreeParserCtxt(ctxt);

    g_fprintf(stderr, "Error retrieving current time.\n");
    return NULL;
  }

  f = rss_parse(filename, root_element, fetched_time);

  xmlFreeDoc(doc);
  xmlFreeParserCtxt(ctxt);
  g_free(fetched_time);

  return f;
}
static gboolean
irc_network_manager_file_parse (EmpathyIrcNetworkManager *self,
                                const gchar *filename,
                                gboolean user_defined)
{
  EmpathyIrcNetworkManagerPriv *priv;
  xmlParserCtxtPtr ctxt;
  xmlDocPtr doc;
  xmlNodePtr networks;
  xmlNodePtr node;

  priv = GET_PRIV (self);

  DEBUG ("Attempting to parse file:'%s'...", filename);

  ctxt = xmlNewParserCtxt ();

  /* Parse and validate the file. */
  doc = xmlCtxtReadFile (ctxt, filename, NULL, 0);
  if (!doc)
    {
      g_warning ("Failed to parse file:'%s'", filename);
      xmlFreeParserCtxt (ctxt);
      return FALSE;
    }

  if (!empathy_xml_validate (doc, IRC_NETWORKS_DTD_FILENAME)) {
    g_warning ("Failed to validate file:'%s'", filename);
    xmlFreeDoc (doc);
    xmlFreeParserCtxt (ctxt);
    return FALSE;
  }

  /* The root node, networks. */
  networks = xmlDocGetRootElement (doc);

  for (node = networks->children; node; node = node->next)
    {
      irc_network_manager_parse_irc_network (self, node, user_defined);
    }

  xmlFreeDoc(doc);
  xmlFreeParserCtxt (ctxt);

  return TRUE;
}
Example #25
0
static gboolean
bt_song_io_native_xml_load (gconstpointer const _self,
    const BtSong * const song, GError ** err)
{
  const BtSongIONativeXML *const self = BT_SONG_IO_NATIVE_XML (_self);
  xmlDocPtr song_doc;
  gchar *const file_name;
  guint len;
  gpointer data;
  gboolean result = FALSE;

  xmlParserCtxtPtr const ctxt = xmlNewParserCtxt ();
  if (!ctxt) {
    GST_WARNING ("failed to create parser context");
    g_set_error (err, G_IO_ERROR, G_IO_ERROR_FAILED,
        "Failed to create parser context.");
    return FALSE;
  }

  g_object_get ((gpointer) self, "file-name", &file_name, "data", &data,
      "data-len", &len, NULL);
  GST_INFO ("native io xml will now load song from \"%s\"",
      file_name ? file_name : "data");

  if (data && len) {
    // parse the file from the memory block
    song_doc = xmlCtxtReadMemory (ctxt, data, len, NULL, NULL, 0L);
  } else {
    // open the file from the file_name argument
    song_doc = xmlCtxtReadFile (ctxt, file_name, NULL, 0L);
  }

  if (song_doc) {
    result = bt_song_io_native_load (song_doc, song, err);
    xmlFreeDoc (song_doc);
  } else {
    bt_song_io_native_load_set_error (ctxt, file_name, err);
  }

  g_free (file_name);
  xmlFreeParserCtxt (ctxt);
  return result;
}
Example #26
0
int initxmlcfg(void** lpCtxt,void** lpxmlDoc)
{
    
    xmlParserCtxtPtr	 ctxt;
    xmlDocPtr		 doc;
    char		*file = "npconf.xml";
        
    ctxt = xmlNewParserCtxt();
      
    doc = xmlCtxtReadFile(ctxt, file, "GBK", XML_PARSE_DTDATTR|XML_PARSE_NOERROR);
    if (doc == NULL)
    {
        printf("Can't parse the content: %s\n", file);
        return 0;
    }
    *lpCtxt   = ctxt;
    *lpxmlDoc = doc;
    return 1;    
}
Example #27
0
File: jsio.c Project: atifs/juise
/*
 * Read RPC reply
 */
static lx_document_t *
js_rpc_get_document (js_session_t *jsp)
{
    lx_document_t *docp = NULL;
    xmlParserCtxt *read_ctxt = xmlNewParserCtxt();

    if (read_ctxt == NULL) {
	jsio_trace("jsio: could not make parser context");
    } else {
	docp = js_document_read(read_ctxt, jsp, "xnm:rpc results", NULL, 0);
	if (docp == NULL) {
	    jsio_trace("jsio: could not read content (null document)");
	}

	js_buffer_close(jsp);
	xmlFreeParserCtxt(read_ctxt);
    }

    return docp;
}
Example #28
0
static dpl_status_t
_multipart_parse_complete(const dpl_ctx_t *ctx,
                          const char *buf, int len)
{
    dpl_status_t          ret = DPL_SUCCESS;
    xmlParserCtxtPtr      ctxt;
    xmlDocPtr             doc;
    xmlNode               *elem;

    if (len == 0)
        return DPL_SUCCESS;

    ctxt = xmlNewParserCtxt();
    if (ctxt == NULL)
        return DPL_FAILURE;

    doc = xmlCtxtReadMemory(ctxt, buf, len, NULL, NULL, 0u);
    if (doc == NULL) {
        xmlFreeParserCtxt(ctxt);
        return DPL_FAILURE;
    }

    elem = xmlDocGetRootElement(doc);
    while (elem != NULL)
    {
        if (elem->type == XML_ELEMENT_NODE)
        {
            if (!strcmp((char *)(elem->name), "Error"))
            {
                ret = DPL_FAILURE;
                break ;
            }
        }
        elem = elem->next;
    }

    xmlFreeDoc(doc);
    xmlFreeParserCtxt(ctxt);

    return ret;
}
Example #29
0
int DPM_parse_tree::Initialize(const char *XMLFileName) { 

   int rc;
   xmlParserCtxtPtr parser_context;

   valid = 0;

   if (! XMLFileName) {
       std::cerr << "ERROR: XML file name is NULL." << std::endl;
       std::cerr.flush();
       rc = -1;
   } else {

       LIBXML_TEST_VERSION

       // Create a parser context.
       if ((parser_context = xmlNewParserCtxt()) == NULL) {
           std::cerr << "ERROR: Out of Memory" << std::endl;
           std::cerr.flush();
           exit(0);
       }

       doc = xmlCtxtReadFile( parser_context, XMLFileName, NULL, XML_PARSE_DTDVALID );

       if (doc == NULL) {
           std::cerr << "ERROR: Parse of XML file \"" << XMLFileName << "\"" << " failed." << std::endl;
           std::cerr.flush();
           rc = -1;
       } else if (parser_context->valid == 0) {
           std::cerr << "WARNING: Validation of XML file \"" << XMLFileName << "\"" << " failed." << std::endl;
           std::cerr.flush();
           rc = 0;
       } else {
           valid = 1;
           rc = 0;
       }
       xmlFreeParserCtxt(parser_context);
   }

   return rc;
}
Example #30
0
int main(int argc, const char *argv[]) {
  int status = 0;
  xmlParserCtxtPtr parser_context = 0;
  xmlDocPtr doc = 0;
  xmlDtdPtr dtd = 0;
  xmlValidCtxtPtr valid_context = 0;

  do {
    if (argc < 3) {
      status = 2;
      fprintf(stderr, "Too few arguments.\n");
      break;
    }

    parser_context = xmlNewParserCtxt();
    doc = xmlCtxtReadFile(parser_context, argv[1], NULL, 0);
    if (!doc) {
      status = 3;
      fprintf(stderr, "Can't read xml.\n");
      break;
    }

    dtd = xmlParseDTD(NULL, (const xmlChar *)argv[2]);
    if (!dtd) {
      status = 4;
      fprintf(stderr, "Can't read dtd.\n");
      break;
    }

    valid_context = xmlNewValidCtxt();
    status = xmlValidateDtd(valid_context, doc, dtd) ? 0 : 1;
  } while (0);

  if (parser_context) xmlFreeParserCtxt(parser_context);
  if (doc) xmlFreeDoc(doc);
  if (dtd) xmlFreeDtd(dtd);
  if (valid_context) xmlFreeValidCtxt(valid_context);

  return status;
}