Example #1
0
YelpTransform
*yelp_transform_new (gchar             *stylesheet,
		     YelpTransformFunc  func,
		     gpointer           user_data)
{
    YelpTransform *transform;
    
    transform = g_new0 (YelpTransform, 1);
    transform->func = func;
    transform->user_data = user_data;

    transform->stylesheet = xsltParseStylesheetFile (BAD_CAST stylesheet);
    if (!transform->stylesheet) {
	transform->error =
	    yelp_error_new (_("Invalid Stylesheet"),
			    _("The XSLT stylesheet ā€˜%sā€™ is either missing, or it is "
			      "not valid."),
			    stylesheet);
	transform_error (transform);
	g_free (transform);
	return NULL;
    }

    transform->queue = g_async_queue_new ();
    transform->chunks = g_hash_table_new_full (g_str_hash,
					       g_str_equal,
					       g_free,
					       NULL);

    return transform;
}
Example #2
0
Xsltproc::ReturnValue Xsltproc::execute()
{
    Xsltproc::ReturnValue retval = Xsltproc::Success;
    try
    {
        if( freopen(mErrorFilename.toUtf8().data(),"w",stderr) == NULL ) throw Xsltproc::GenericFailure;

        mStylesheet = xsltParseStylesheetFile( (const xmlChar*)mStyleSheetFilename.toUtf8().data() );
        if(mStylesheet == 0) throw Xsltproc::InvalidStylesheet;

        mXml = xmlParseFile( (const char*)mXmlFilename.toUtf8().data() );
        if(mXml == 0) throw Xsltproc::InvalidXmlFile;

        mOutput = xsltApplyStylesheet(mStylesheet, mXml, (const char**)mParams);
        if(mOutput == 0) throw Xsltproc::GenericFailure;

        FILE *foutput = 0;
        foutput = fopen(mOutputFilename.toUtf8().data(),"w");
        if( foutput == 0 ) throw Xsltproc::CouldNotOpenOutput;
        xsltSaveResultToFile(foutput, mOutput, mStylesheet);
        fclose(foutput);
    }
    catch(Xsltproc::ReturnValue e)
    {
        retval = e;
    }

    fclose(stderr);

    freeResources();

    return retval;
}
Example #3
0
int main( int argc, char *argv[] )
{
	if( argc != 3 ) {
		std::cerr << "usage: testlibxslt1 <XSLT file> <XML file>" << std::endl;
		return 1;
	}

	LIBXML_TEST_VERSION
	
	xsltStylesheetPtr script = xsltParseStylesheetFile( ( const xmlChar *)argv[1] );
	xmlDocPtr doc = xmlParseFile( argv[2] );
	const char *params[1] = { NULL };
	xmlDocPtr res = xsltApplyStylesheet( script, doc, params );

	xmlChar *resTxt;
	int resLen;
	xsltSaveResultToString( &resTxt, &resLen, res, script );
	std::cout << resTxt;

	xmlFreeDoc( res );
	xmlFreeDoc( doc );
	xsltFreeStylesheet( script );

	xsltCleanupGlobals( );
	xmlCleanupParser( );

	return 0;
}
Example #4
0
    std::string parse(const std::string& xml, const std::string& name, const std::string& url, const std::string& html, const std::string& htmlheader, std::vector<std::pair<std::string, std::string> >& attaches) {
        std::string ret("");

        std::string pp = getParserPath(url);
        xsltStylesheetPtr xslt = xsltParseStylesheetFile(BAD_CAST pp.c_str());
        htmlDocPtr doc = NULL;
        static std::string encoding("gb18030");
        std::string mimetype = getMIMEType(htmlheader, html);
        if (!mimetype.empty() && mimetype == "text/xml") {
            doc = html.empty() ? NULL : xmlReadDoc(BAD_CAST html.c_str(), NULL, encoding.c_str(), XML_PARSE_RECOVER);
        } else {
            doc = html.empty() ? NULL : htmlParseDoc(BAD_CAST html.c_str(), encoding.c_str());
        }
        if (doc != NULL) {
            const char *params[7] = {0};
            size_t n_param = 0;
            params[n_param] = NULL;
            xmlDocPtr res = xsltApplyStylesheet(xslt, doc, params);
            //free_xslt_params(params, n_param);
            if (res != NULL) {
                xmlChar *s = NULL;
                int len = 0;
                if (xsltSaveResultToString(&s, &len, res, xslt) >= 0) {
                    ret.assign((const char *)s, len);
                    xmlFree(s);
                }
                xmlFreeDoc(res);
            }
            xmlFreeDoc(doc);
        }
        return ret;
    }
Example #5
0
ReturnCode xsltTransformToFile(xmlDocPtr doc, const char *xslFilename, const char *outputFilename) {
    xmlDocPtr res;
    xsltStylesheetPtr style;

    if( (xslFilename == NULL) || (outputFilename == NULL) ) {
        printMsg(MESSAGETYPE_ERROR, "xsltTransformToFile: Null pointer error");
        return FAILED;
    }

    style = xsltParseStylesheetFile ((const xmlChar *) xslFilename);
    if (style == NULL) {
        printMsg(MESSAGETYPE_ERROR, "xsltTransformToFile: Could not parse XSLT file: %s", xslFilename);
        return FAILED;
    }

    res = xsltApplyStylesheet(style, doc, NULL);
    if(res == NULL){
        printMsg(MESSAGETYPE_ERROR, "xsltTransformToFile: Problem applying stylesheet");
        return FAILED;
    }

    xsltSaveResultToFilename(outputFilename, res, style, 0);
    xmlFreeDoc(res);
    xsltFreeStylesheet(style);
    return SUCCESS;
}
Example #6
0
int main(int argc, char **argv) {
     xsltStylesheetPtr stylesheet = NULL;
     xmlDocPtr doc, res;
     char* stylesheetfile;
     char* infile;
     char *outfile;

     if (argc!=4) {
         printf("XSLT Transform\n2009 by thom using libxml2\nUsage:\n\txslt-transform <stylesheet> <infile> <outfile>\n");
         exit(1);
     }

     stylesheetfile = argv[1];
     infile = argv[2];
     outfile = argv[3];


     xmlSubstituteEntitiesDefault(1);
     xmlLoadExtDtdDefaultValue = 1;
     stylesheet = xsltParseStylesheetFile(BAD_CAST stylesheetfile);
     doc = xmlParseFile(infile);
     res = xsltApplyStylesheet(stylesheet, doc, 0);
     printf("use \"%s\" to transform \"%s\" to \"%s\" ...\n", stylesheetfile, infile, outfile);
     xsltSaveResultToFilename(outfile, res, stylesheet, 0);
     xsltFreeStylesheet(stylesheet);
     xmlFreeDoc(res);
     xmlFreeDoc(doc);
     xsltCleanupGlobals();
     xmlCleanupParser();
     printf("\tDone.\n");
     exit(0);
}
Example #7
0
static xsltStylesheetPtr xslt_get_stylesheet(const char *fn) {
    int i;
    int empty = -1;
    struct stat file;

    if(stat(fn, &file)) {
        WARN2("Error checking for stylesheet file \"%s\": %s", fn, 
                strerror(errno));
        return NULL;
    }

    for(i=0; i < CACHESIZE; i++) {
        if(cache[i].filename)
        {
#ifdef _WIN32
            if(!stricmp(fn, cache[i].filename))
#else
            if(!strcmp(fn, cache[i].filename))
#endif
            {
                if(file.st_mtime > cache[i].last_modified)
                {
                    xsltFreeStylesheet(cache[i].stylesheet);

                    cache[i].last_modified = file.st_mtime;
                    cache[i].stylesheet = xsltParseStylesheetFile(XMLSTR(fn));
                    cache[i].cache_age = time(NULL);
                }
                DEBUG1("Using cached sheet %i", i);
                return cache[i].stylesheet;
            }
        }
        else
            empty = i;
    }

    if(empty>=0)
        i = empty;
    else
        i = evict_cache_entry();

    cache[i].last_modified = file.st_mtime;
    cache[i].filename = strdup(fn);
    cache[i].stylesheet = xsltParseStylesheetFile(XMLSTR(fn));
    cache[i].cache_age = time(NULL);
    return cache[i].stylesheet;
}
void Docbook2XhtmlGeneratorJob::run()
{
  UMLDoc* umlDoc = UMLApp::app()->document();
  xsltStylesheetPtr cur = NULL;
  xmlDocPtr doc, res;

  const char *params[16 + 1];
  int nbparams = 0;
  params[nbparams] = NULL;

  umlDoc->writeToStatusBar(i18n("Exporting to XHTML..."));

  QString xsltFileName(KGlobal::dirs()->findResource("appdata", QLatin1String("docbook2xhtml.xsl")));
  uDebug() << "XSLT file is'" << xsltFileName << "'";
  QFile xsltFile(xsltFileName);
  xsltFile.open(QIODevice::ReadOnly);
  QString xslt = QString::fromLatin1(xsltFile.readAll());
  uDebug() << "XSLT is'" << xslt << "'";
  xsltFile.close();

  QString localXsl = KGlobal::dirs()->findResource("data", QLatin1String("ksgmltools2/docbook/xsl/html/docbook.xsl"));
  uDebug() << "Local xsl is'" << localXsl << "'";
  if (!localXsl.isEmpty())
  {
    localXsl = QLatin1String("href=\"file://") + localXsl + QLatin1String("\"");
    xslt.replace(QRegExp(QLatin1String("href=\"http://[^\"]*\"")), localXsl);
  }
  KTemporaryFile tmpXsl;
  tmpXsl.setAutoRemove(false);
  tmpXsl.open();
  QTextStream str (&tmpXsl);
  str << xslt;
  str.flush();

  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 1;
  uDebug() << "Parsing stylesheet " << tmpXsl.fileName();
  cur = xsltParseStylesheetFile((const xmlChar *)tmpXsl.fileName().toLatin1().constData());
  uDebug() << "Parsing file " << m_docbookUrl.path();
  doc = xmlParseFile((const char*)(m_docbookUrl.path().toUtf8()));
  uDebug() << "Applying stylesheet ";
  res = xsltApplyStylesheet(cur, doc, params);

  KTemporaryFile tmpXhtml;
  tmpXhtml.setAutoRemove(false);
  tmpXhtml.open();

  uDebug() << "Writing HTML result to temp file: " << tmpXhtml.fileName();
  xsltSaveResultToFd(tmpXhtml.handle(), res, cur);

  xsltFreeStylesheet(cur);
  xmlFreeDoc(res);
  xmlFreeDoc(doc);

  xsltCleanupGlobals();
  xmlCleanupParser();

  emit xhtmlGenerated(tmpXhtml.fileName());
}
Example #9
0
clish_xslt_t *clish_xslt_read(const char *filename)
{
	xsltStylesheet* cur = NULL;

	cur = xsltParseStylesheetFile((const xmlChar *)filename);

	return xsltStylesheet_to_xslt(cur);
}
Example #10
0
void ExportDialog::accept()
{
    QDialog::accept();

    if (ui->csvRadio->isChecked()) {
        /// Find the CSV filter in the standard filter list
        //!@todo: good and clean solution
        QStringList defaultFilters = KEduVocDocument::pattern(KEduVocDocument::Writing).split('\n');
        QString filter = defaultFilters.filter(QStringLiteral("csv")).join(QStringLiteral("\n"));
        QUrl filename = getFileName(filter);
        if (filename != QUrl()) {
            m_doc->saveAs(filename);
        }
        return;
    }

    QString xslFile;
    if (ui->flashCardRadio->isChecked()) {
        xslFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("parley/xslt/flashcards.xsl"));
    } else {
        xslFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("parley/xslt/table.xsl"));
    }

    QString filter = "*.html|" + i18n("HTML document");
    QUrl filename = getFileName(filter);
    if (filename.isEmpty()) {
        return;
    }

    qDebug() << "XSLT starting";

    xsltStylesheetPtr cur = NULL;
    xmlDocPtr doc, res;

    xmlSubstituteEntitiesDefault(1);
    xmlLoadExtDtdDefaultValue = 1;
    cur = xsltParseStylesheetFile((const xmlChar*) xslFile.toLatin1().constData());

    doc = xmlParseDoc((const xmlChar*) m_doc->document()->toByteArray(m_doc->document()->generator()).constData());

    res = xsltApplyStylesheet(cur, doc, 0);
    FILE* result = fopen(QFile::encodeName(filename.toLocalFile()).constData(), "w");
    if (result != NULL) {
        xsltSaveResultToFile(result, res, cur);
        fclose(result);
    } else {
        KMessageBox::error(this, i18n("Could not write to file \"%1\"", filename.toLocalFile()));
    }

    xsltFreeStylesheet(cur);
    xmlFreeDoc(res);
    xmlFreeDoc(doc);

    xsltCleanupGlobals();
    xmlCleanupParser();

    qDebug() << "XSLT finished";
}
Example #11
0
/**
 * Sets the style file
 *
 * \param xsldoc Either a filename or source of XSL file
 */
void CXSLTransform::SetXSLDoc(CString xsldoc)
{
	if (m_XSLDoc.Compare(xsldoc) != 0) {
		m_XSLDoc = xsldoc;
		Reset();
		if (xsldoc.IsEmpty()) {
			return;
		}
		xmlErrorPtr err = NULL;

		xmlDocPtr xsl = NULL;
		CFileFind ff;
		if (xsldoc.GetLength() < MAX_PATH && ff.FindFile(xsldoc)) {
			// xsldoc is a filename
			ff.Close();
			m_Style = xsltParseStylesheetFile((const xmlChar *)(LPCSTR)xsldoc);
			if (!m_Style || m_Style->errors > 0) {
				xmlFreeDoc(xsl);
				err = xmlGetLastError();
				if (err != NULL)
					m_LastError.Format(AfxLoadString(IDS_STRING_XSLPARSEERR), err->file, err->line, err->int2, err->code, err->message);
				else
					m_LastError.LoadString(IDS_STRING_UNKNOWN_XSLERROR);
				xmlResetLastError();
#ifdef _DEBUG
				TRACE1("CXSLTransform::SetXSLDoc(): %s\n", m_LastError);
#endif
			}
		} else {
			// xsldoc is a XSL source
			xsl = xmlParseMemory(xsldoc, xsldoc.GetLength());
			if (xsl) {
				m_Style = xsltParseStylesheetDoc(xsl);
				if (!m_Style || m_Style->errors > 0) {
					xmlFreeDoc(xsl);
					err = xmlGetLastError();
					if (err != NULL)
						m_LastError.Format(AfxLoadString(IDS_STRING_XSLPARSEERR), err->file, err->line, err->int2, err->code, err->message);
					else
						m_LastError.LoadString(IDS_STRING_UNKNOWN_XSLERROR);
					xmlResetLastError();
#ifdef _DEBUG
					TRACE1("CXSLTransform::SetXSLDoc(): %s\n", m_LastError);
#endif
				}
			} else {
				// XML parsing error
				err = xmlGetLastError();
				m_LastError.Format(AfxLoadString(IDS_STRING_XMLPARSEERR), err->file, err->line, err->int2, err->code, err->message);
				xmlResetLastError();
#ifdef _DEBUG
				TRACE1("CXSLTransform::SetXSLDoc(): %s\n", m_LastError);
#endif
			}
		}
	}
}
Example #12
0
static gchar *
update_apply_xslt (updateJobPtr job)
{
	xsltStylesheetPtr	xslt = NULL;
	xmlOutputBufferPtr	buf;
	xmlDocPtr		srcDoc = NULL, resDoc = NULL;
	gchar			*output = NULL;

	g_assert (NULL != job->result);
	
	do {
		srcDoc = xml_parse (job->result->data, job->result->size, NULL);
		if (!srcDoc) {
			g_warning("fatal: parsing request result XML source failed (%s)!", job->request->filtercmd);
			break;
		}

		/* load localization stylesheet */
		xslt = xsltParseStylesheetFile (job->request->filtercmd);
		if (!xslt) {
			g_warning ("fatal: could not load filter stylesheet \"%s\"!", job->request->filtercmd);
			break;
		}

		resDoc = xsltApplyStylesheet (xslt, srcDoc, NULL);
		if (!resDoc) {
			g_warning ("fatal: applying stylesheet \"%s\" failed!", job->request->filtercmd);
			break;
		}

		buf = xmlAllocOutputBuffer (NULL);
		if (-1 == xsltSaveResultTo (buf, resDoc, xslt)) {
			g_warning ("fatal: retrieving result of filter stylesheet failed (%s)!", job->request->filtercmd);
			break;
		}
		
#ifdef LIBXML2_NEW_BUFFER
		if (xmlOutputBufferGetSize (buf) > 0)
			output = xmlCharStrdup (xmlOutputBufferGetContent (buf));
#else
		if (xmlBufferLength (buf->buffer) > 0)
			output = xmlCharStrdup (xmlBufferContent (buf->buffer));
#endif
 
		xmlOutputBufferClose (buf);
	} while (FALSE);

	if (srcDoc)
		xmlFreeDoc (srcDoc);
	if (resDoc)
		xmlFreeDoc (resDoc);
	if (xslt)
		xsltFreeStylesheet (xslt);
	
	return output;
}
Example #13
0
/**********************************************************************
print_xml_filename_to_filename_using_stylesheet

Print the contents of an XML file to another file applying an 
XSLT stylesheet.

Returns TRUE if successful, FALSE otherwise.
**********************************************************************/
BOOLEAN_T print_xml_filename_to_filename_using_stylesheet(
    char* input_file_path,        /* path to XML input file IN */
    char* stylesheet_file_path,   /* path to MEME XSL stylesheet IN */
    char* output_file_path        /* path to HTML output file IN */
) {

  xsltStylesheetPtr stylesheet = NULL;
  xmlDocPtr input_doc = NULL;
  xmlDocPtr output_doc = NULL;
  const int PERFORM_ENTITY_SUBST = 1;

  xmlSubstituteEntitiesDefault(PERFORM_ENTITY_SUBST);
  xmlLoadExtDtdDefaultValue = 0;
  exsltRegisterAll();

  stylesheet = xsltParseStylesheetFile((const xmlChar *) stylesheet_file_path);
  if (!stylesheet) {
    fprintf(stderr, "Unable to parse stylesheet %s.\n", stylesheet_file_path);
    return FALSE;
  }
  input_doc = xmlParseFile(input_file_path);
  if (!input_doc) {
    fprintf(stderr, "Unable to parse input file %s.\n", input_file_path);
    return FALSE;
  }
  output_doc = xsltApplyStylesheet(stylesheet, input_doc, NULL);
  if (!output_doc) {
    fprintf(
      stderr, 
      "Unable to apply stylsheet %s to input from file %s.\n", 
      stylesheet_file_path,
      input_file_path
    );
    return FALSE;
  }
  int result = xsltSaveResultToFilename(output_file_path, output_doc, stylesheet, 0);
  if (result == -1) {
    fprintf(
      stderr, 
      "Unable to save result of applying stylesheet %s to %s.\n", 
      stylesheet_file_path, 
      output_file_path
    );
  }

  xsltFreeStylesheet(stylesheet);
  xmlFreeDoc(output_doc);
  xmlFreeDoc(input_doc);
  xsltCleanupGlobals();
  xmlCleanupParser();

  return TRUE;

} /* print_xml_file_html */
Example #14
0
static xsltStylesheetPtr
render_load_stylesheet (const gchar *xsltName)
{
	xsltStylesheetPtr	i18n_filter;
	xsltStylesheetPtr	xslt;
	xmlDocPtr		xsltDoc, resDoc;
	gchar			*filename;

	if (!stylesheets)
		render_init ();

	/* try to serve the stylesheet from the cache */
	xslt = (xsltStylesheetPtr)g_hash_table_lookup (stylesheets, xsltName);
	if (xslt)
		return xslt;

	/* or load and translate it... */

	/* 1. load localization stylesheet */
	i18n_filter = xsltParseStylesheetFile (PACKAGE_DATA_DIR G_DIR_SEPARATOR_S PACKAGE G_DIR_SEPARATOR_S "xslt" G_DIR_SEPARATOR_S "i18n-filter.xslt");
	if (!i18n_filter) {
		g_warning ("fatal: could not load localization stylesheet!");
		return NULL;
	}

	/* 2. load and localize the rendering stylesheet */
	filename = g_strjoin (NULL, PACKAGE_DATA_DIR G_DIR_SEPARATOR_S PACKAGE G_DIR_SEPARATOR_S "xslt" G_DIR_SEPARATOR_S, xsltName, ".xml", NULL);
	xsltDoc = xmlParseFile (filename);
	if (!xsltDoc)
		g_warning ("fatal: could not load rendering stylesheet (%s)!", xsltName);

	g_free (filename);

	resDoc = xsltApplyStylesheet (i18n_filter, xsltDoc, (const gchar **)langParams->params);
	if (!resDoc)
		g_warning ("fatal: applying localization stylesheet failed (%s)!", xsltName);

	/* Use the following to debug XSLT transformation problems */
	/* xsltSaveResultToFile (stdout, resDoc, i18n_filter); */

	/* 3. create localized rendering stylesheet */
	xslt = xsltParseStylesheetDoc(resDoc);
	if (!xslt)
		g_warning("fatal: could not load rendering stylesheet (%s)!", xsltName);

	xmlFreeDoc (xsltDoc);
	xsltFreeStylesheet (i18n_filter);

	g_hash_table_insert (stylesheets, g_strdup (xsltName), xslt);
	
	return xslt;
}
Example #15
0
void transform(fs::path xslt, std::string inputfile, std::string outputfile)
{
    auto stylesheet = xsltParseStylesheetFile(BAD_CAST xslt.c_str());
    auto doc = xmlParseFile(inputfile.c_str());

    const char *params = NULL;
    auto result = xsltApplyStylesheet(stylesheet, doc, &params);
    xsltSaveResultToFilename(outputfile.c_str(), result, stylesheet, 0);

    xmlFreeDoc(doc);
    xmlFreeDoc(result);
    xsltFreeStylesheet(stylesheet);
}
Example #16
0
/**
 * Extrae la cadena original del comprobante fiscal
 *
 * La funcion regresa:
 *
 *	0	En caso de generar la cadena original exitosamente,
 *
 * y en caso de error:
 *
 *	1	Cuando la stylsheet, proporcionada para generar la cadena
 *		original no pudo ser compilada.
 *	2	Cuando las transformaciones, definidas en la stylesheet
 *		indicada no pudieron aplicarse al CFDi.
 *	3	No fue posible escribir la cadena original a un buffer
 *
 */
int
genera_cadena_original(const char *stylesheet, xmlDocPtr doc, xmlChar** cadena, int verbose)
{
  xsltStylesheetPtr style = NULL;
  xmlDocPtr result = NULL;
  int cadena_len = 0;
  int out = 0;

  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 1;

  xsltSetGenericErrorFunc(stderr, local_error_function);

  style = xsltParseStylesheetFile((const xmlChar *)stylesheet);
  if ( style == NULL ) {
    if ( verbose ) {
      fprintf(stderr, "%s:%d Ocurrio un Error. Stylesheet (%s) no analizada.\n", __FILE__, __LINE__, stylesheet);
    }
    xsltCleanupGlobals();
    return 1;
  }

  result = xsltApplyStylesheet(style, doc, NULL);
  if ( result == NULL ) {
    if ( verbose ) {
      fprintf(stderr, "%s:%d Ocurrio un Error. Transformaciones de stylesheet (%s) no aplicadas.\n", __FILE__, __LINE__, stylesheet);
    }
    xsltFreeStylesheet(style);
    xsltCleanupGlobals();
    return 2;
  }

  out = xsltSaveResultToString(cadena, &cadena_len, result, style);
  if ( out == -1 ) {
    if ( verbose ) {
      fprintf(stderr, "%s:%d Ocurrio un error. Error al salvar la cadena original en el buffer.\n", __FILE__, __LINE__);
    }
    return 3;
  }

  xsltFreeStylesheet(style);
  xmlFreeDoc(result);

  if ( verbose ) {
    printf("%s:%d Cadena original de la informaciĆ³n del comprobante:\n%s\n", __FILE__, __LINE__, *cadena);
  }

  xsltCleanupGlobals();

  return 0;
}
Example #17
0
/* thread to read xsl file and add to the cache */
void *xslt_update (void *arg)
{
    xsl_req *x = arg;
    client_t *client = x->client;
    char *fn = x->cache.filename;
    xsltStylesheetPtr sheet;

    xmlSetStructuredErrorFunc ("xsl/file", config_xml_parse_failure);
    xsltSetGenericErrorFunc ("", log_parse_failure);

    sheet = x->cache.stylesheet = xsltParseStylesheetFile (XMLSTR(fn));
    if (sheet)
    {
        int i;

        INFO1 ("loaded stylesheet %s", x->cache.filename);
        if (sheet->mediaType && strcmp ((char*)sheet->mediaType, "text/html") != 0)
        {
            // avoid this lookup for html pages
            const char _hdr[] = "Content-Disposition: attachment; filename=\"file.";
            const size_t _hdrlen = sizeof (_hdr);
            size_t len = _hdrlen + 12;
            char *filename = malloc (len); // enough for name and extension
            strcpy (filename, _hdr);
            fserve_write_mime_ext ((char*)sheet->mediaType, filename + _hdrlen - 1, len - _hdrlen - 4);
            strcat (filename, "\"\r\n");
            x->cache.disposition = filename;
        }
        // we now have a sheet, find and update.
        thread_rwlock_wlock (&xslt_lock);
        i = xslt_cached (fn, &x->cache, time(NULL));
        xslt_send_sheet (client, x->doc, i);
    }
    else
    {
        WARN1 ("problem reading stylesheet \"%s\"", x->cache.filename);
        free (fn);
        xmlFreeDoc (x->doc);
        free (x->cache.disposition);
        client->shared_data = NULL;
        client_send_404 (client, "Could not parse XSLT file");
    }
    thread_spin_lock (&update_lock);
    xsl_updating--;
    thread_spin_unlock (&update_lock);
    free (x);
    return NULL;
}
Example #18
0
int main(int argc, char *argv[])
{
  xsltStylesheetPtr cur = NULL;
  xmlDocPtr doc, res;

  const char *params[16 + 1];
  int nbparams = 0;
  params[nbparams] = NULL;

  KAboutData aboutData( "umbodoc", 0, ki18n("Umbrello UML Modeller autonomous code generator"),
                        umbrelloVersion(), ki18n(description), KAboutData::License_GPL,
                        ki18n("(c) 2006 Gael de Chalendar (aka Kleag), (c) 2002-2006 Umbrello UML Modeller Authors"), KLocalizedString(),
                        "http://uml.sf.net/");
  aboutData.addAuthor(ki18n("Gael de Chalendar (aka Kleag)"),KLocalizedString(), "*****@*****.**");
  aboutData.addAuthor(ki18n("Umbrello UML Modeller Authors"), KLocalizedString(), "*****@*****.**");
  KCmdLineArgs::init( argc, argv, &aboutData );

  KCmdLineOptions options;
  options.add("+[File]", ki18n("File to transform"));
  options.add("xslt <url>", ki18n("The XSLT file to use"));
  KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  QCStringList xsltOpt = args->getOptionList("xslt");
  if (xsltOpt.size() > 0)
  {
    QString xsltFile(xsltOpt.last());

    xmlSubstituteEntitiesDefault(1);
    xmlLoadExtDtdDefaultValue = 1;
    cur = xsltParseStylesheetFile((const xmlChar *)xsltFile.latin1());
    doc = xmlParseFile(args->url( 0 ).url().latin1());
    res = xsltApplyStylesheet(cur, doc, params);
    xsltSaveResultToFile(stdout, res, cur);

    xsltFreeStylesheet(cur);
    xmlFreeDoc(res);
    xmlFreeDoc(doc);

    xsltCleanupGlobals();
    xmlCleanupParser();
  }
  return(0);
}
Example #19
0
/**
 * Initialize an xml stylesheet structure to some sane starting values.
 * @param   xsl The stylesheet to initialize.
 * @return  @c TRUE if successful, @c FALSE if an error occurs.
 * @ingroup EXML_XSLT_Group
 */
int exml_xsl_init( EXML_XSL *xsl, char *filename )
{
	CHECK_PARAM_POINTER_RETURN("xsl", xsl, FALSE);

	xmlSubstituteEntitiesDefault(1);

	xmlLoadExtDtdDefaultValue = 1;

	xsl->buffers = ecore_list_new();
	ecore_list_free_cb_set(xsl->buffers, ECORE_FREE_CB(xmlFree));

	xsl->cur = xsltParseStylesheetFile((const xmlChar *) filename);

	if( !xsl->cur )
		return FALSE;

	return TRUE;
}
int main(int argc, char* argv[]) {

  char* usage = "xsltpro_lite <xslt filename> <xml input filename> <output filename>\n";

  if (argc != 4) {
    fprintf(stderr, "%s", usage);
    exit(0);
  }

  char* stylesheet_file_path = argv[1]; // Path to XSLT stylesheet
  char* input_file_path = argv[2];      // Path to XML input file IN
  char* output_file_path = argv[3];      // Path to XML input file IN

  xsltStylesheetPtr stylesheet = NULL;
  xmlDocPtr input_doc = NULL;
  xmlDocPtr output_doc = NULL;
  const int PERFORM_ENTITY_SUBST = 1;
  xmlSubstituteEntitiesDefault(PERFORM_ENTITY_SUBST);
  xmlLoadExtDtdDefaultValue = 0;
  exsltRegisterAll();
  stylesheet = xsltParseStylesheetFile((xmlChar *) stylesheet_file_path);
  if (! stylesheet) {
    fprintf(stderr, "Couldn't parse stylesheet file %s\n", stylesheet_file_path);
    exit(1);
  }
  input_doc = xmlParseFile(input_file_path);
  if (! stylesheet) {
    fprintf(stderr, "Couldn't parse input file %s\n", input_file_path);
    exit(1);
  }
  output_doc = xsltApplyStylesheet(stylesheet, input_doc, NULL);
  if (! output_doc) {
    fprintf(stderr, "Couldn't apply stylesheet %s to input file %s\n",
      stylesheet_file_path, input_file_path);
    exit(1);
  }
  xsltSaveResultToFilename(output_file_path, output_doc, stylesheet, 0);
  xmlFreeDoc(output_doc);
  xmlFreeDoc(input_doc);
  xsltFreeStylesheet(stylesheet);

  exit(0);

}; 
Example #21
0
xsltStylesheetPtr parse_xsl( char* xsl, int iXslType ) {
  xsltStylesheetPtr tParsedXslt   = NULL;
  xmlDocPtr         tXSLDocument  = NULL;
  
  /** Rem: For encoding */
  xmlCharEncodingHandlerPtr encoder = NULL;
  const xmlChar *encoding = NULL;
  
  /** Act: Encoding support */
  xmlInitCharEncodingHandlers( );

  /** Act: Parse XSL */
  if( iXslType == RUBY_XSLT_XSLSRC_TYPE_STR ) {
    tXSLDocument = xmlParseMemory( xsl, strlen( xsl ) );
    if( tXSLDocument == NULL ) {
      rb_raise( eXSLTParsingError, "XSL parsing error" );
      return( NULL );
    }

    tParsedXslt = xsltParseStylesheetDoc( tXSLDocument );
  } else if( iXslType == RUBY_XSLT_XSLSRC_TYPE_FILE ) {
    tParsedXslt = xsltParseStylesheetFile( BAD_CAST xsl );
  }

  if( tParsedXslt == NULL ) {
    rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" );
    return( NULL );
  }
    
  /** Act: Get encoding */
  XSLT_GET_IMPORT_PTR( encoding, tParsedXslt, encoding )
  encoder = xmlFindCharEncodingHandler((char *)encoding);
  
  if( encoding != NULL ) {
    encoder = xmlFindCharEncodingHandler((char *)encoding);
    if( (encoder != NULL) && (xmlStrEqual((const xmlChar *)encoder->name, (const xmlChar *) "UTF-8")) ) {
      encoder = NULL;
    }
  }
  
  return( tParsedXslt );
}
Example #22
0
static xsltStylesheetPtr try_get_stylesheet(const char *path, int len, const char *name)
{
	xsltStylesheetPtr ret;
	int namelen = strlen(name);
	char *filename = malloc(len+1+namelen+1);

	if (!filename)
		return NULL;

	memcpy(filename, path, len);
	filename[len] = G_DIR_SEPARATOR;
	memcpy(filename + len + 1, name, namelen+1);

	ret = NULL;
	if (!access(filename, R_OK))
		ret = xsltParseStylesheetFile(filename);
	free(filename);

	return ret;
}
Example #23
0
/**********************************************************************
print_meme_file_html

Print MEME results in HTML format.
Format XML as HTML using a stylesheet and an XSLT
**********************************************************************/
extern void print_meme_file_html(
    char* stylesheet_file_path,   /* path to MEME XSL stylesheet IN */
    char* input_file_path,        /* path to XML input file IN */
    char* output_file_path        /* path to HTML output file IN */
) {
  xsltStylesheetPtr stylesheet = NULL;
  xmlDocPtr input_doc = NULL;
  xmlDocPtr output_doc = NULL;
  const int PERFORM_ENTITY_SUBST = 1;
  xmlSubstituteEntitiesDefault(PERFORM_ENTITY_SUBST);
  xmlLoadExtDtdDefaultValue = 0;
  exsltRegisterAll();
  stylesheet = xsltParseStylesheetFile((const xmlChar *) stylesheet_file_path);
  input_doc = xmlParseFile(input_file_path);
  output_doc = xsltApplyStylesheet(stylesheet, input_doc, NULL);
  xsltSaveResultToFilename(output_file_path, output_doc, stylesheet, 0);
  xmlFreeDoc(output_doc);
  xmlFreeDoc(input_doc);
  xsltFreeStylesheet(stylesheet);

} /* print_meme_file_html */
Example #24
0
FILE* graphml_parse(FILE * fp) {
  extern int xmlLoadExtDtdDefaultValue;

  FILE* retval = (FILE*) fp;
  /* read contents of fp. */

  /* try to transform to .gv using libxslt
     and pipe the resulting .gv-formatted string into a new fp. */

  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 1;

  xsltStylesheetPtr cur = NULL;
  xmlDocPtr doc, res;

  cur = xsltParseStylesheetFile("graphml2gv.xsl");

  /* otherwise, rewind fp to beginning of file and return it. */

  return retval;
}
Example #25
0
/* thread to read xsl file and add to the cache */
void *xslt_update (void *arg)
{
    xsl_req *x = arg;
    client_t *client = x->client;
    worker_t *worker = client ? client->worker : NULL;
    char *fn = x->cache.filename;

    x->cache.stylesheet = xsltParseStylesheetFile (XMLSTR(fn));
    if (x->cache.stylesheet)
    {
        int i = x->index;

        if (client) fn = strdup (fn); // need to copy the filename if another lookup is to do
        INFO1 ("loaded stylesheet %s", x->cache.filename);
        thread_rwlock_wlock (&xslt_lock);
        free (cache[i].filename);
        xsltFreeStylesheet (cache[i].stylesheet);
        memcpy (&cache[i], &x->cache, sizeof (stylesheet_cache_t));
        thread_rwlock_unlock (&xslt_lock);
        memset (&x->cache, 0, sizeof (stylesheet_cache_t));

        if (client)
        {
            x->cache.filename = fn;
            client->flags |= CLIENT_ACTIVE;
        }
    }
    else
    {
        WARN1 ("problem reading stylesheet \"%s\"", x->cache.filename);
        free (fn);
        if (client) client_send_404 (client, "Could not parse XSLT file");
    }
    thread_spin_lock (&update_lock);
    xsl_updating--;
    thread_spin_unlock (&update_lock);
    if (worker) worker_wakeup (worker); // wakeup after the decrease or it may delay
    if (client == NULL) free (x);
    return NULL;
}
Example #26
0
char* xsltTransformToString(xmlDocPtr doc, const char *xslFilename) {
    xmlDocPtr res;
    xmlChar *string;
	int len;
	xsltStylesheetPtr style;

    style = xsltParseStylesheetFile ((const xmlChar *) xslFilename);
    if (style == NULL) {
        printMsg(MESSAGETYPE_ERROR, "xsltTransformToString: Could not parse XSLT file");
        return NULL;
    }

    res = xsltApplyStylesheet(style, doc, NULL);
    if(res == NULL) {
        printMsg(MESSAGETYPE_ERROR, "xsltTransformToString: Problem applying stylesheet");
        return NULL;
    }

    xsltSaveResultToString(&string, &len, res, style);
    xmlFreeDoc(res);
    return (char *) string;
}
Example #27
0
gboolean 
gtodo_client_export(GTodoClient *source, GFile *dest, const gchar *path_to_xsl, gchar **params, GError **error)
{
	xsltStylesheetPtr cur;
	xmlChar *string;
	xmlDocPtr res;
	int length;
	GError *err;

	g_return_val_if_fail(path_to_xsl != NULL, FALSE);

	cur= xsltParseStylesheetFile(BAD_CAST (path_to_xsl));

	if (params == NULL)
	{
		res = xsltApplyStylesheet(cur, source->gtodo_doc, NULL);
	}
	else
	{
		res = xsltApplyStylesheet(cur, source->gtodo_doc, (const char **)params);
	}

	xsltSaveResultToString (&string, &length, res, cur);

	if (!g_file_replace_contents (dest, (char *)string, length, NULL, FALSE,
			G_FILE_CREATE_NONE, NULL, NULL, &err))
	{
		DEBUG_PRINT ("Error exporting file: %s", 
				err->message);
		g_propagate_error (error, err);
	}

	xmlFree (string);
	xsltFreeStylesheet (cur);
	xmlFreeDoc (res);
	xsltCleanupGlobals ();

	return TRUE;
}
Example #28
0
static void
parse_and_load(void)
{
	char *name;
	char *uuid;
	xmlNode *cur_node;
	xmlNode *dep_node;
        xsltStylesheetPtr ss;
	const char *params[1];

	qb_enter();

	ss = xsltParseStylesheetFile(BAD_CAST "/usr/share/pacemaker-cloud/cf2pe.xsl");
	params[0] = NULL;

        _pe = xsltApplyStylesheet(ss, _config, params);
        xsltFreeStylesheet(ss);
        dep_node = xmlDocGetRootElement(_config);

	application = calloc(1, sizeof(struct application));

	name = (char*)xmlGetProp(dep_node, BAD_CAST "name");
	application->name = strdup(name);
	uuid = (char*)xmlGetProp(dep_node, BAD_CAST "uuid");
	application->uuid = strdup(uuid);

        for (cur_node = dep_node->children; cur_node;
             cur_node = cur_node->next) {
                if (cur_node->type == XML_ELEMENT_NODE) {
                        if (strcmp((char*)cur_node->name, "assemblies") == 0) {
				assemblies_create(cur_node->children);
                        }
                }
        }

	qb_leave();
}
Example #29
0
// Processes input XML file (e.g., instance metadata) into output XML file or string (e.g., for libvirt)
// using XSL-T specification file (e.g., libvirt.xsl)
static int apply_xslt_stylesheet (const char * xsltStylesheetPath, const char * inputXmlPath, const char * outputXmlPath, char * outputXmlBuffer, int outputXmlBufferSize)
{
        int err = OK;

        INIT();
        xsltStylesheetPtr cur = xsltParseStylesheetFile ((const xmlChar *)xsltStylesheetPath);
        if (cur) {
                xmlDocPtr doc = xmlParseFile (inputXmlPath);
                if (doc) {
                        xsltTransformContextPtr ctxt = xsltNewTransformContext (cur, doc); // need context to get result
                        xsltSetCtxtParseOptions (ctxt, 0); // TODO: do we want any XSL-T parsing options?
                        xmlDocPtr res = xsltApplyStylesheetUser (cur, doc, NULL, NULL, NULL, ctxt); // applies XSLT to XML
                        int applied_ok = ctxt->state==XSLT_STATE_OK; // errors are communicated via ctxt->state
                        xsltFreeTransformContext (ctxt);
                        
                        if (res && applied_ok) {

                            // save to a file, if path was provied
                            if (outputXmlPath!=NULL) {
                                FILE * fp = fopen (outputXmlPath, "w");
                                if (fp) {
                                    int bytes = xsltSaveResultToFile (fp, res, cur);
                                    if (bytes==-1) {
                                        logprintfl (EUCAERROR, "ERROR: failed to save XML document to %s\n", outputXmlPath);
                                        err = ERROR;
                                    }
                                    fclose (fp);
                                } else {
                                    logprintfl (EUCAERROR, "ERROR: failed to create file %s\n", outputXmlPath);
                                    err = ERROR;
                                }                                
                            }

                            // convert to an ASCII buffer, if such was provided
                            if (err==OK && outputXmlBuffer!=NULL && outputXmlBufferSize > 0) {
                                xmlChar * buf;
                                int buf_size;
                                if (xsltSaveResultToString (&buf, &buf_size, res, cur)==0) { // success
                                    if (buf_size < outputXmlBufferSize) {
                                        bzero (outputXmlBuffer, outputXmlBufferSize);
                                        for (int i=0, j=0; i<buf_size; i++) {
                                            char c = (char) buf [i];
                                            if (c != '\n') // remove newlines
                                                outputXmlBuffer [j++] = c;
                                        }
                                    } else {
                                        logprintfl (EUCAERROR, "ERROR: XML string buffer is too small (%d > %d)\n", buf_size, outputXmlBufferSize);
                                        err = ERROR;
                                    }
                                    xmlFree (buf);
                                } else {
                                    logprintfl (EUCAERROR, "ERROR: failed to save XML document to a string\n");
                                    err = ERROR;
                                }
                            }
                        } else {
                            logprintfl (EUCAERROR, "ERROR: failed to apply stylesheet %s to %s\n", xsltStylesheetPath, inputXmlPath);
                            err = ERROR;
                        }
                        if (res!=NULL) xmlFreeDoc(res);
                        xmlFreeDoc(doc);
                } else {
                        logprintfl (EUCAERROR, "ERROR: failed to parse XML document %s\n", inputXmlPath);
                        err = ERROR;
                }
                xsltFreeStylesheet(cur);
        } else {
                logprintfl (EUCAERROR, "ERROR: failed to open and parse XSL-T stylesheet file %s\n", xsltStylesheetPath);
                err = ERROR;
        }

        return err;
}
Example #30
0
normalize_record_t normalize_record_create(struct conf_service *service,
                                           const char *spec)
{
    NMEM nmem = nmem_create();
    normalize_record_t nt = nmem_malloc(nmem, sizeof(*nt));
    struct normalize_step **m = &nt->steps;
    int no_errors = 0;
    int embed = 0;

    if (*spec == '<')
        embed = 1;

    nt->nmem = nmem;

    if (embed)
    {
        xmlDoc *xsp_doc = xmlParseMemory(spec, strlen(spec));

        if (!xsp_doc)
            no_errors++;
        {
            *m = nmem_malloc(nt->nmem, sizeof(**m));
            (*m)->marcmap = NULL;
            (*m)->stylesheet = NULL;
            (*m)->stylesheet2 = NULL;


            (*m)->stylesheet = xsltParseStylesheetDoc(xsp_doc);
            if (!(*m)->stylesheet)
                no_errors++;
            m = &(*m)->next;
        }
    }
    else
    {
        struct conf_config *conf = service->server->config;
        int i, num;
        char **stylesheets;
        nmem_strsplit(nt->nmem, ",", spec, &stylesheets, &num);

        for (i = 0; i < num; i++)
        {
            WRBUF fname = conf_get_fname(conf, stylesheets[i]);

            *m = nmem_malloc(nt->nmem, sizeof(**m));
            (*m)->marcmap = NULL;
            (*m)->stylesheet = NULL;

            (*m)->stylesheet2 = service_xslt_get(service, stylesheets[i]);
            if ((*m)->stylesheet2)
                ;
            else if (!strcmp(&stylesheets[i][strlen(stylesheets[i])-4], ".xsl"))
            {
                if (!((*m)->stylesheet =
                      xsltParseStylesheetFile((xmlChar *) wrbuf_cstr(fname))))
                {
                    yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load stylesheet: %s",
                            stylesheets[i]);
                    no_errors++;
                }
            }
            else if (!strcmp(&stylesheets[i][strlen(stylesheets[i])-5], ".mmap"))
            {
                if (!((*m)->marcmap = marcmap_load(wrbuf_cstr(fname), nt->nmem)))
                {
                    yaz_log(YLOG_FATAL|YLOG_ERRNO, "Unable to load marcmap: %s",
                            stylesheets[i]);
                    no_errors++;
                }
            }
            else
            {
                yaz_log(YLOG_FATAL, "Cannot handle stylesheet: %s", stylesheets[i]);
                no_errors++;
            }

            wrbuf_destroy(fname);
            m = &(*m)->next;
        }
    }
    *m = 0;  /* terminate list of steps */

    if (no_errors)
    {
        normalize_record_destroy(nt);
        nt = 0;
    }
    return nt;
}