string XMLFunctions::xslt(string &data, string &style, ServerInterface &srvInterface) { xmlDocPtr doc; /* the resulting document tree */ xmlDocPtr styeSheet; /* the resulting document tree */ xsltStylesheetPtr ssPtr; const char *params[1]; int nbparams = 0; params[nbparams] = NULL; doc = xmlReadMemory(data.c_str(), data.size(), "noname.xml", NULL, 0); // xmlNode *root_element = NULL; // root_element = xmlDocGetRootElement(doc); // print_element_names(root_element); styeSheet = xmlReadMemory(style.c_str(), style.length(), "noname.xml", NULL, 0); ssPtr = xsltParseStylesheetDoc (styeSheet); xmlDocPtr result = xsltApplyStylesheet(ssPtr, doc, params); xmlChar * resultString; int stringLen; xsltSaveResultToString(&resultString, &stringLen, result, ssPtr); return string((char*) resultString); }
/* call-seq: * stylesheet.output(doc) => string * * Output an xml document, usually the result of an xslt * transformation, and return the result as a string. Output will be * done according to the output specification in the xslt * stylesheet. Note that this includes the encoding of the string. */ VALUE ruby_xslt_stylesheet_output(VALUE self, VALUE document) { // FIXME: set string encoding in ruby 1.9? xmlDocPtr xdoc; xsltStylesheetPtr xstylesheet; xmlChar *result = NULL; int len = 0, bytes = 0; VALUE rresult; if (!rb_obj_is_kind_of(document, cXMLDocument)) rb_raise(rb_eTypeError, "Must pass in an XML::Document instance."); Data_Get_Struct(document, xmlDoc, xdoc); Data_Get_Struct(self, xsltStylesheet, xstylesheet); bytes = xsltSaveResultToString(&result, &len, xdoc, xstylesheet); if ( bytes == -1 ) { rb_raise(rb_eRuntimeError, "error dumping document"); } rresult=rb_str_new((const char*)result,len); xmlFree(result); return rresult; }
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; }
Variant c_XSLTProcessor::t_transformtoxml(const Object& doc) { if (doc.instanceof(c_DOMDocument::classof())) { c_DOMDocument *domdoc = doc.getTyped<c_DOMDocument>(); m_doc = xmlCopyDoc ((xmlDocPtr)domdoc->m_node, /*recursive*/ 1); xmlDocPtr res = apply_stylesheet(); if (res == nullptr) { return false; } xmlChar *mem; int size; if (xsltSaveResultToString(&mem, &size, res, m_stylesheet) < 0) { if (mem) { xmlFree(mem); } return false; } String ret = String((char*)mem, size, CopyString); xmlFree(mem); return ret; } return false; }
bool XSLTUtils::XSLTTransform(std::string& output) { const char *params[16+1]; params[0] = NULL; m_xmlOutput = xsltApplyStylesheet(m_xsltStylesheet, m_xmlInput, params); if (!m_xmlOutput) { CLog::Log(LOGDEBUG, "XSLT: xslt transformation failed"); return false; } xmlChar *xmlResultBuffer = NULL; int xmlResultLength = 0; int res = xsltSaveResultToString(&xmlResultBuffer, &xmlResultLength, m_xmlOutput, m_xsltStylesheet); if (res == -1) { xmlFree(xmlResultBuffer); return false; } output.append((const char *)xmlResultBuffer, xmlResultLength); xmlFree(xmlResultBuffer); return true; }
static Variant HHVM_METHOD(XSLTProcessor, transformToXML, const Object& doc) { auto data = Native::data<XSLTProcessorData>(this_); if (doc.instanceof(s_DOMDocument)) { auto domdoc = Native::data<DOMNode>(doc); data->m_doc = libxml_register_node(xmlCopyDoc ((xmlDocPtr)domdoc->nodep(), /*recursive*/ 1)); xmlDocPtr res = data->apply_stylesheet(); if (res == nullptr) { return false; } xmlChar *mem; int size; if (xsltSaveResultToString(&mem, &size, res, data->m_stylesheet) < 0) { if (mem) { xmlFree(mem); } return false; } String ret = String((char*)mem, size, CopyString); xmlFree(mem); return ret; } return false; }
QString XSLTransformer::transform(const QString &xml, QHash<QString, QString> const ¶ms) const { // Read XML data intro an xmlDoc. QByteArray xmlData(xml.toUtf8()); QScopedPointer<xmlDoc, XmlDocDeleter> doc( xmlReadMemory(xmlData.constData(), xmlData.size(), 0, 0, 0)); if (!doc) throw std::runtime_error("XSLTransformer::transform: Could not open XML data"); // Hmpf, data conversions. char const **cParams = new char const *[params.size() * 2 + 1]; int i = 0; for (QHash<QString, QString>::const_iterator iter = params.constBegin(); iter != params.constEnd(); ++iter) { QByteArray keyData(iter.key().toUtf8()); QByteArray valueData(iter.value().toUtf8()); char const *cKey = strdup(keyData.constData()); char const *cValue = strdup(valueData.constData()); cParams[i] = cKey; cParams[i + 1] = cValue; i += 2; } cParams[params.size() * 2] = 0; // Terminator QScopedPointer<xsltTransformContext, XsltTransformContextDeleter> ctx( xsltNewTransformContext(d_xslPtr.data(), doc.data())); xsltSetCtxtParseOptions(ctx.data(), XSLT_PARSE_OPTIONS); // Transform... QScopedPointer<xmlDoc, XmlDocDeleter> res( xsltApplyStylesheetUser(d_xslPtr.data(), doc.data(), cParams, NULL, NULL, ctx.data())); if (!res) throw std::runtime_error("XSLTransformer::transform: Could not apply transformation!"); else if (ctx->state != XSLT_STATE_OK) throw std::runtime_error("XSLTransformer::transform: Transformation error, check your query!"); xmlChar *outputBare = 0; int outputLen = -1; xsltSaveResultToString(&outputBare, &outputLen, res.data(), d_xslPtr.data()); QScopedPointer<xmlChar, XmlDeleter> output(outputBare); if (!output) throw std::runtime_error("Could not apply stylesheet!"); QString result(QString::fromUtf8(reinterpret_cast<char const *>(output.data()))); // Deallocate parameter memory for (int i = 0; i < params.size() * 2; ++i) free(const_cast<char *>(cParams[i])); delete[] cParams; return result; }
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; }
/** * Return the result as string */ CString CXSLTransform::AsString() { int buffsize = 100; xmlChar *buff;// = (xmlChar*)malloc((size_t)buffsize); int i = xsltSaveResultToString(&buff, &buffsize, m_Result, m_Style); CString res(buff); // free(buff); return res; }
static int convert_xslt(void *vinfo, WRBUF record, WRBUF wr_error) { int ret = 0; struct xslt_info *info = vinfo; xmlDocPtr doc = xmlParseMemory(wrbuf_buf(record), wrbuf_len(record)); if (!doc) { wrbuf_printf(wr_error, "xmlParseMemory failed"); ret = -1; } else { xmlDocPtr xsp_doc = xmlCopyDoc(info->xsp_doc, 1); xsltStylesheetPtr xsp = xsltParseStylesheetDoc(xsp_doc); xmlDocPtr res = xsltApplyStylesheet(xsp, doc, info->xsl_parms); if (res) { xmlChar *out_buf = 0; int out_len; #if HAVE_XSLTSAVERESULTTOSTRING xsltSaveResultToString(&out_buf, &out_len, res, xsp); #else xmlDocDumpFormatMemory (res, &out_buf, &out_len, 1); #endif if (!out_buf) { wrbuf_printf(wr_error, "xsltSaveResultToString failed"); ret = -1; } else { wrbuf_rewind(record); wrbuf_write(record, (const char *) out_buf, out_len); xmlFree(out_buf); } xmlFreeDoc(res); } else { wrbuf_printf(wr_error, "xsltApplyStylesheet failed"); ret = -1; } xmlFreeDoc(doc); xsltFreeStylesheet(xsp); /* frees xsp_doc too */ } return ret; }
/** * 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; }
/* * call-seq: * serialize(document) * * Serialize +document+ to an xml string. */ static VALUE serialize(VALUE self, VALUE xmlobj) { xmlDocPtr xml ; xsltStylesheetPtr ss ; xmlChar* doc_ptr ; int doc_len ; VALUE rval ; Data_Get_Struct(xmlobj, xmlDoc, xml); Data_Get_Struct(self, xsltStylesheet, ss); xsltSaveResultToString(&doc_ptr, &doc_len, xml, ss); rval = NOKOGIRI_STR_NEW(doc_ptr, doc_len); xmlFree(doc_ptr); return rval ; }
/* * call-seq: * serialize(document) * * Serialize +document+ to an xml string. */ static VALUE serialize(VALUE self, VALUE xmlobj) { xmlDocPtr xml ; nokogiriXsltStylesheetTuple *wrapper; xmlChar* doc_ptr ; int doc_len ; VALUE rval ; Data_Get_Struct(xmlobj, xmlDoc, xml); Data_Get_Struct(self, nokogiriXsltStylesheetTuple, wrapper); xsltSaveResultToString(&doc_ptr, &doc_len, xml, wrapper->ss); rval = NOKOGIRI_STR_NEW(doc_ptr, doc_len); xmlFree(doc_ptr); return rval ; }
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client) { xmlDocPtr res; xsltStylesheetPtr cur; xmlChar *string; int len, problem = 0; xmlSetGenericErrorFunc ("", log_parse_failure); xsltSetGenericErrorFunc ("", log_parse_failure); thread_mutex_lock(&xsltlock); cur = xslt_get_stylesheet(xslfilename); if (cur == NULL) { thread_mutex_unlock(&xsltlock); ERROR1 ("problem reading stylesheet \"%s\"", xslfilename); client_send_404 (client, "Could not parse XSLT file"); return; } res = xsltApplyStylesheet(cur, doc, NULL); if (xsltSaveResultToString (&string, &len, res, cur) < 0) problem = 1; thread_mutex_unlock(&xsltlock); if (problem == 0) { const char *http = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: "; int buf_len = strlen (http) + 20 + len; if (string == NULL) string = xmlStrdup (""); client->respcode = 200; client_set_queue (client, NULL); client->refbuf = refbuf_new (buf_len); len = snprintf (client->refbuf->data, buf_len, "%s%d\r\n\r\n%s", http, len, string); client->refbuf->len = len; fserve_add_client (client, NULL); xmlFree (string); } else { WARN1 ("problem applying stylesheet \"%s\"", xslfilename); client_send_404 (client, "XSLT problem"); } xmlFreeDoc(res); }
static void * threadRoutine1(void *data) { xmlDocPtr input; xmlDocPtr style; xmlDocPtr res; xmlChar *result; int len; xsltStylesheetPtr cur; int id = (int)(unsigned long) data; input = xmlReadMemory(doc, strlen(doc), "doc.xml", NULL, 0); if (input == NULL) { fprintf(stderr, "Thread id %d failed to parse input\n", id); exit(1); } style = xmlReadMemory(stylesheet, strlen(stylesheet), "doc.xsl", NULL, 0); if (style == NULL) { fprintf(stderr, "Thread id %d failed to parse stylesheet\n", id); exit(1); } cur = xsltParseStylesheetDoc(style); if (cur == NULL) { fprintf(stderr, "Thread id %d failed to compile stylesheet\n", id); exit(1); } res = xsltApplyStylesheet(cur, input, NULL); if (res == NULL) { fprintf(stderr, "Thread id %d failed to apply stylesheet\n", id); exit(1); } if (xsltSaveResultToString(&result, &len, res, cur) < 0) { fprintf(stderr, "Thread id %d failed to output result\n", id); exit(1); } if (!xmlStrEqual(BAD_CAST expect, result)) { fprintf(stderr, "Thread id %d output not conform\n", id); exit(1); } xsltFreeStylesheet(cur); xmlFreeDoc(input); xmlFreeDoc(res); xmlFree(result); return(0); }
/** * xOut = parser( char *xml, int iXmlType, char *xslt, int iXslType, char **pxParams ); */ char* parse( xsltStylesheetPtr tParsedXslt, xmlDocPtr tXMLDocument, char **pxParams ) { xmlDocPtr tXMLDocumentResult = NULL; int iXMLDocumentResult; xmlChar *tXMLDocumentResultString; int tXMLDocumentResultLenght; tXMLDocumentResult = xsltApplyStylesheet( tParsedXslt, tXMLDocument, (const char**) pxParams ); if( tXMLDocumentResult == NULL ) { rb_raise( eXSLTTransformationError, "Stylesheet transformation error" ); return( NULL ); } iXMLDocumentResult = xsltSaveResultToString( &tXMLDocumentResultString, &tXMLDocumentResultLenght, tXMLDocumentResult, tParsedXslt ); xmlFreeDoc(tXMLDocumentResult); return((char*)tXMLDocumentResultString); }
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; }
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; }
/** * Write the transformed xml document out to a memory location. * @param xml The xml document * @param xsl The xml stylesheet * @param params The transform parameters * @param ptr The source xml output location * @param len The size of the memory buffer * @return a pointer to the memory location, or NULL if * @ingroup EXML_XSLT_Group */ void *exml_transform_mem_write( EXML *xml, EXML_XSL *xsl, const char *params[], ssize_t *len ) { xmlDocPtr res, doc; xmlChar *buf; int ret; CHECK_PARAM_POINTER_RETURN("xml", xml, NULL); CHECK_PARAM_POINTER_RETURN("xsl", xsl, NULL); exml_doc_write(xml, &doc); res = xsltApplyStylesheet(xsl->cur, doc, params); xmlFreeDoc(doc); if( !res ) { return NULL; } ret = xsltSaveResultToString(&buf, len, res, xsl->cur); xmlFreeDoc(res); if( ret < 0 ) { *len = 0; xsltCleanupGlobals(); return NULL; } ecore_list_append( xsl->buffers, buf ); xsltCleanupGlobals(); return buf; }
static void * threadRoutine2(void *data) { xmlDocPtr input; xmlDocPtr res; xmlChar *result; int len; xsltStylesheetPtr cur = (xsltStylesheetPtr) data; if (cur == NULL) { fprintf(stderr, "Thread failed to get the stylesheet\n"); exit(1); } input = xmlReadMemory(doc, strlen(doc), "doc.xml", NULL, 0); if (input == NULL) { fprintf(stderr, "Thread failed to parse input\n"); exit(1); } res = xsltApplyStylesheet(cur, input, NULL); if (res == NULL) { fprintf(stderr, "Thread failed to apply stylesheet\n"); exit(1); } if (xsltSaveResultToString(&result, &len, res, cur) < 0) { fprintf(stderr, "Thread failed to output result\n"); exit(1); } if (!xmlStrEqual(BAD_CAST expect, result)) { fprintf(stderr, "Thread output not conform\n"); exit(1); } xmlFreeDoc(input); xmlFreeDoc(res); xmlFree(result); return(0); }
/* * Internal handler function */ static Datum handler_internal(Oid function_oid, FunctionCallInfo fcinfo, bool execute) { HeapTuple proctuple; Form_pg_proc pg_proc_entry; char *sourcecode; Datum prosrcdatum; bool isnull; const char **xslt_params; int i; Oid *argtypes; char **argnames; char *argmodes; int numargs; xmlDocPtr ssdoc; xmlDocPtr xmldoc; xmlDocPtr resdoc; xsltStylesheetPtr stylesheet; int reslen; xmlChar *resstr; Datum resdatum; if (CALLED_AS_TRIGGER(fcinfo)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("trigger functions not supported"))); proctuple = SearchSysCache(PROCOID, ObjectIdGetDatum(function_oid), 0, 0, 0); if (!HeapTupleIsValid(proctuple)) elog(ERROR, "cache lookup failed for function %u", function_oid); prosrcdatum = SysCacheGetAttr(PROCOID, proctuple, Anum_pg_proc_prosrc, &isnull); if (isnull) elog(ERROR, "null prosrc"); sourcecode = pstrdup(DatumGetCString(DirectFunctionCall1(textout, prosrcdatum))); /* allow one blank line at the start */ if (sourcecode[0] == '\n') sourcecode++; numargs = get_func_arg_info(proctuple, &argtypes, &argnames, &argmodes); if (numargs < 1) ereport(ERROR, (errmsg("XSLT function must have at least one argument"))); if (argtypes[0] != XMLOID) ereport(ERROR, (errmsg("first argument of XSLT function must have type XML"))); #if 0 xsltSetGenericErrorFunc(NULL, xmlGenericError); #endif ssdoc = xmlParseDoc((xmlChar *) sourcecode); /* XXX use backend's xml_parse here() */ stylesheet = xsltParseStylesheetDoc(ssdoc); /* XXX check error handling */ if (!stylesheet) ereport(ERROR, (errmsg("could not parse stylesheet"))); pg_proc_entry = (Form_pg_proc) GETSTRUCT(proctuple); { char *method; method = (char *) stylesheet->method; /* * TODO: This is strictly speaking not correct because the * default output method may be "html", but that can only * detected at run time, so punt for now. */ if (!method) method = "xml"; if (strcmp(method, "xml") == 0 && pg_proc_entry->prorettype != XMLOID) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("XSLT stylesheet has output method \"xml\" but return type of function is not xml"))); else if ((strcmp(method, "html") == 0 || strcmp(method, "text") == 0) && pg_proc_entry->prorettype != TEXTOID && pg_proc_entry->prorettype != VARCHAROID) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("XSLT stylesheet has output method \"%s\" but return type of function is not text or varchar", method))); } /* validation stops here */ if (!execute) { ReleaseSysCache(proctuple); PG_RETURN_VOID(); } /* execution begins here */ xslt_params = palloc(((numargs - 1) * 2 + 1) * sizeof(*xslt_params)); for (i = 0; i < numargs-1; i++) { xslt_params[i*2] = argnames[i+1]; xslt_params[i*2+1] = type_to_cstring(PG_GETARG_DATUM(i+1), argtypes[i+1]); } xslt_params[i*2] = NULL; { xmltype *arg0 = PG_GETARG_XML_P(0); // XXX this ought to use xml_parse() xmldoc = xmlParseMemory((char *) VARDATA(arg0), VARSIZE(arg0) - VARHDRSZ); } resdoc = xsltApplyStylesheet(stylesheet, xmldoc, xslt_params); if (!resdoc) elog(ERROR, "xsltApplyStylesheet() failed"); xmlFreeDoc(xmldoc); if (xsltSaveResultToString(&resstr, &reslen, resdoc, stylesheet) != 0) elog(ERROR, "result serialization failed"); xsltFreeStylesheet(stylesheet); xmlFreeDoc(resdoc); xsltCleanupGlobals(); xmlCleanupParser(); resdatum = cstring_to_type(resstr ? (char *) resstr : "", pg_proc_entry->prorettype); ReleaseSysCache(proctuple); PG_RETURN_DATUM(resdatum); }
static void xslt_yelp_document (xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr comp) { YelpTransform *transform; xmlChar *page_id = NULL; gchar *temp; xmlChar *page_buf; gint buf_size; xsltStylesheetPtr style = NULL; const char *old_outfile; xmlDocPtr new_doc = NULL; xmlDocPtr old_doc; xmlNodePtr old_insert; debug_print (DB_FUNCTION, "entering\n"); if (ctxt->state == XSLT_STATE_STOPPED) return; if (!ctxt || !node || !inst || !comp) return; transform = (YelpTransform *) ctxt->_private; page_id = xsltEvalAttrValueTemplate (ctxt, inst, (const xmlChar *) "href", NULL); if (page_id == NULL || *page_id == '\0') { if (page_id) xmlFree (page_id); else xsltTransformError (ctxt, NULL, inst, _("No href attribute found on " "yelp:document\n")); /* FIXME: put a real error here */ goto done; } debug_print (DB_ARG, " page_id = \"%s\"\n", page_id); old_outfile = ctxt->outputFile; old_doc = ctxt->output; old_insert = ctxt->insert; ctxt->outputFile = (const char *) page_id; style = xsltNewStylesheet (); if (style == NULL) { xsltTransformError (ctxt, NULL, inst, _("Out of memory")); goto done; } style->omitXmlDeclaration = TRUE; new_doc = xmlNewDoc (BAD_CAST "1.0"); new_doc->charset = XML_CHAR_ENCODING_UTF8; new_doc->dict = ctxt->dict; xmlDictReference (new_doc->dict); ctxt->output = new_doc; ctxt->insert = (xmlNodePtr) new_doc; xsltApplyOneTemplate (ctxt, node, inst->children, NULL, NULL); xsltSaveResultToString (&page_buf, &buf_size, new_doc, style); ctxt->outputFile = old_outfile; ctxt->output = old_doc; ctxt->insert = old_insert; g_mutex_lock (transform->mutex); temp = g_strdup ((gchar *) page_id); xmlFree (page_id); g_async_queue_push (transform->queue, g_strdup ((gchar *) temp)); g_hash_table_insert (transform->chunks, temp, page_buf); transform->idle_funcs++; g_idle_add ((GSourceFunc) transform_chunk, transform); g_mutex_unlock (transform->mutex); done: if (new_doc) xmlFreeDoc (new_doc); if (style) xsltFreeStylesheet (style); }
wxString frmReport::XslProcessReport(const wxString &xml, const wxString &xsl) { xmlChar *output = 0; xmlDocPtr ssDoc = 0, xmlDoc = 0, resDoc = 0; xsltStylesheetPtr ssPtr = 0; int length; wxBeginBusyCursor(); // Apply the stylesheet xmlSubstituteEntitiesDefault (1); // Substitute entities xmlLoadExtDtdDefaultValue = 1; // Load external entities // Parse the stylesheet ssDoc = xmlParseDoc(XML_FROM_WXSTRING(xsl)); if (!ssDoc) { wxEndBusyCursor(); wxLogError(_("Failed to parse the XML stylesheet!")); goto cleanup; } ssPtr = xsltParseStylesheetDoc(ssDoc); if (!ssPtr) { wxEndBusyCursor(); wxLogError(_("Failed to parse the XSL stylesheet!")); goto cleanup; } // Parse the data xmlDoc = xmlParseDoc(XML_FROM_WXSTRING(xml)); if (!xmlDoc) { wxEndBusyCursor(); wxLogError(_("Failed to parse the XML document!")); goto cleanup; } // Apply the stylesheet resDoc = xsltApplyStylesheet(ssPtr, xmlDoc, NULL); if (!resDoc) { wxEndBusyCursor(); wxLogError(_("Failed to apply the XSL stylesheet to the XML document!")); goto cleanup; } // Get the result xsltSaveResultToString (&output, &length, resDoc, ssPtr); if (!resDoc) { wxEndBusyCursor(); wxLogError(_("Failed to read the processed document!")); goto cleanup; } cleanup: // Cleanup if (resDoc) xmlFreeDoc(resDoc); if (xmlDoc) xmlFreeDoc(xmlDoc); if (ssPtr) xsltFreeStylesheet(ssPtr); // This crashes - dunno why :-( // if (ssDoc) // xmlFreeDoc(ssDoc); xsltCleanupGlobals(); wxEndBusyCursor(); if (output) return WXSTRING_FROM_XML(output); else return wxEmptyString; }
static char *uwsgi_xslt_apply(char *xmlfile, char *xsltfile, char *params, int *rlen) { char **vparams = NULL; char *tmp_params = NULL; uint16_t count = 0; if (params) { // first count the number of items size_t i; size_t params_len = strlen(params); for(i=0;i<params_len;i++) { if (params[i] == '=') { count++; } } vparams = uwsgi_calloc( sizeof(char *) * ((count * 2) + 1)); tmp_params = uwsgi_str(params); char *p = strtok(tmp_params, "&"); int pos = 0; while(p) { char *equal = strchr(p, '='); if (equal) { *equal = 0; vparams[pos] = p; pos++; vparams[pos] = uwsgi_concat3("\"", equal+1, "\""); pos++; } p = strtok(NULL, "&"); } } // we reset them every time to avoid collision with other xml engines xmlSubstituteEntitiesDefault(1); xmlLoadExtDtdDefaultValue = 1; xmlDocPtr doc = xmlParseFile(xmlfile); if (!doc) { if (vparams) { int i; for(i=1;i<(count*2);i+=2) free(vparams[i]); free(tmp_params); free(vparams); } return NULL; } xsltStylesheetPtr ss = xsltParseStylesheetFile((const xmlChar *) xsltfile); if (!ss) { xmlFreeDoc(doc); if (vparams) { int i; for(i=1;i<(count*2);i+=2) free(vparams[i]); free(tmp_params); free(vparams); } return NULL; } xmlDocPtr res = xsltApplyStylesheet(ss, doc, (const char **) vparams); if (!res) { xsltFreeStylesheet(ss); xmlFreeDoc(doc); if (vparams) { int i; for(i=1;i<(count*2);i+=2) free(vparams[i]); free(tmp_params); free(vparams); } return NULL; } xmlChar *output; int ret = xsltSaveResultToString(&output, rlen, res, ss); xsltFreeStylesheet(ss); xmlFreeDoc(res); xmlFreeDoc(doc); if (vparams) { int i; for(i=1;i<(count*2);i+=2) free(vparams[i]); free(tmp_params); free(vparams); } if (ret < 0) return NULL; return (char *) output; }
Datum xslt_process(PG_FUNCTION_ARGS) { text *doct = PG_GETARG_TEXT_P(0); text *ssheet = PG_GETARG_TEXT_P(1); text *paramstr; const char *params[MAXPARAMS + 1]; /* +1 for the terminator */ xsltStylesheetPtr stylesheet = NULL; xmlDocPtr doctree; xmlDocPtr restree; xmlDocPtr ssdoc = NULL; xmlChar *resstr; int resstat; int reslen; if (fcinfo->nargs == 3) { paramstr = PG_GETARG_TEXT_P(2); parse_params(params, paramstr); } else /* No parameters */ params[0] = NULL; /* Setup parser */ pgxml_parser_init(); /* Check to see if document is a file or a literal */ if (VARDATA(doct)[0] == '<') doctree = xmlParseMemory((char *) VARDATA(doct), VARSIZE(doct) - VARHDRSZ); else doctree = xmlParseFile(text_to_cstring(doct)); if (doctree == NULL) { xmlCleanupParser(); elog_error(ERROR, "error parsing XML document", 0); PG_RETURN_NULL(); } /* Same for stylesheet */ if (VARDATA(ssheet)[0] == '<') { ssdoc = xmlParseMemory((char *) VARDATA(ssheet), VARSIZE(ssheet) - VARHDRSZ); if (ssdoc == NULL) { xmlFreeDoc(doctree); xmlCleanupParser(); elog_error(ERROR, "error parsing stylesheet as XML document", 0); PG_RETURN_NULL(); } stylesheet = xsltParseStylesheetDoc(ssdoc); } else stylesheet = xsltParseStylesheetFile((xmlChar *) text_to_cstring(ssheet)); if (stylesheet == NULL) { xmlFreeDoc(doctree); xsltCleanupGlobals(); xmlCleanupParser(); elog_error(ERROR, "failed to parse stylesheet", 0); PG_RETURN_NULL(); } restree = xsltApplyStylesheet(stylesheet, doctree, params); resstat = xsltSaveResultToString(&resstr, &reslen, restree, stylesheet); xsltFreeStylesheet(stylesheet); xmlFreeDoc(restree); xmlFreeDoc(doctree); xsltCleanupGlobals(); xmlCleanupParser(); if (resstat < 0) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text_with_len((char *) resstr, reslen)); }
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client) { xmlDocPtr res; xsltStylesheetPtr cur; xmlChar *string; int len, problem = 0; const char *mediatype = NULL; const char *charset = NULL; xmlSetGenericErrorFunc ("", log_parse_failure); xsltSetGenericErrorFunc ("", log_parse_failure); thread_mutex_lock(&xsltlock); cur = xslt_get_stylesheet(xslfilename); if (cur == NULL) { thread_mutex_unlock(&xsltlock); ICECAST_LOG_ERROR("problem reading stylesheet \"%s\"", xslfilename); client_send_404 (client, "Could not parse XSLT file"); return; } res = xsltApplyStylesheet(cur, doc, NULL); if (xsltSaveResultToString (&string, &len, res, cur) < 0) problem = 1; /* lets find out the content type and character encoding to use */ if (cur->encoding) charset = (char *)cur->encoding; if (cur->mediaType) mediatype = (char *)cur->mediaType; else { /* check method for the default, a missing method assumes xml */ if (cur->method && xmlStrcmp (cur->method, XMLSTR("html")) == 0) mediatype = "text/html"; else if (cur->method && xmlStrcmp (cur->method, XMLSTR("text")) == 0) mediatype = "text/plain"; else mediatype = "text/xml"; } if (problem == 0) { ssize_t ret; int failed = 0; refbuf_t *refbuf; size_t full_len = strlen (mediatype) + len + 1024; if (full_len < 4096) full_len = 4096; refbuf = refbuf_new (full_len); if (string == NULL) string = xmlCharStrdup (""); ret = util_http_build_header(refbuf->data, full_len, 0, 0, 200, NULL, mediatype, charset, NULL, NULL); if (ret == -1) { ICECAST_LOG_ERROR("Dropping client as we can not build response headers."); client_send_500(client, "Header generation failed."); } else { if ( full_len < (ret + len + 64) ) { void *new_data; full_len = ret + len + 64; new_data = realloc(refbuf->data, full_len); if (new_data) { ICECAST_LOG_DEBUG("Client buffer reallocation succeeded."); refbuf->data = new_data; refbuf->len = full_len; ret = util_http_build_header(refbuf->data, full_len, 0, 0, 200, NULL, mediatype, charset, NULL, NULL); if (ret == -1) { ICECAST_LOG_ERROR("Dropping client as we can not build response headers."); client_send_500(client, "Header generation failed."); failed = 1; } } else { ICECAST_LOG_ERROR("Client buffer reallocation failed. Dropping client."); client_send_500(client, "Buffer reallocation failed."); failed = 1; } } if (!failed) { snprintf(refbuf->data + ret, full_len - ret, "Content-Length: %d\r\n\r\n%s", len, string); client->respcode = 200; client_set_queue (client, NULL); client->refbuf = refbuf; refbuf->len = strlen (refbuf->data); fserve_add_client (client, NULL); } } xmlFree (string); } else { ICECAST_LOG_WARN("problem applying stylesheet \"%s\"", xslfilename); client_send_404 (client, "XSLT problem"); } thread_mutex_unlock (&xsltlock); xmlFreeDoc(res); }
void xslt_transform(xmlDocPtr doc, const char *xslfilename, client_t *client) { xmlDocPtr res; xsltStylesheetPtr cur; xmlChar *string; int len, problem = 0; const char *mediatype = NULL; xmlSetGenericErrorFunc ("", log_parse_failure); xsltSetGenericErrorFunc ("", log_parse_failure); thread_mutex_lock(&xsltlock); cur = xslt_get_stylesheet(xslfilename); if (cur == NULL) { thread_mutex_unlock(&xsltlock); ERROR1 ("problem reading stylesheet \"%s\"", xslfilename); client_send_404 (client, "Could not parse XSLT file"); return; } res = xsltApplyStylesheet(cur, doc, NULL); if (xsltSaveResultToString (&string, &len, res, cur) < 0) problem = 1; /* lets find out the content type to use */ if (cur->mediaType) mediatype = (char *)cur->mediaType; else { /* check method for the default, a missing method assumes xml */ if (cur->method && xmlStrcmp (cur->method, XMLSTR("html")) == 0) mediatype = "text/html"; else if (cur->method && xmlStrcmp (cur->method, XMLSTR("text")) == 0) mediatype = "text/plain"; else mediatype = "text/xml"; } if (problem == 0) { /* the 100 is to allow for the hardcoded headers */ unsigned int full_len = strlen (mediatype) + len + 256; refbuf_t *refbuf = refbuf_new (full_len); ssize_t ret; if (string == NULL) string = xmlCharStrdup (""); ret = util_http_build_header(refbuf->data, full_len, 0, 0, 200, NULL, mediatype, NULL, NULL); snprintf (refbuf->data + ret, full_len - ret, "Content-Length: %d\r\n\r\n%s", len, string); client->respcode = 200; client_set_queue (client, NULL); client->refbuf = refbuf; refbuf->len = strlen (refbuf->data); fserve_add_client (client, NULL); xmlFree (string); } else { WARN1 ("problem applying stylesheet \"%s\"", xslfilename); client_send_404 (client, "XSLT problem"); } thread_mutex_unlock (&xsltlock); xmlFreeDoc(res); }
static ngx_buf_t * ngx_http_xslt_apply_stylesheet(ngx_http_request_t *r, ngx_http_xslt_filter_ctx_t *ctx) { int len, rc, doc_type; u_char *type, *encoding; ngx_buf_t *b; ngx_uint_t i; xmlChar *buf; xmlDocPtr doc, res; ngx_http_xslt_sheet_t *sheet; ngx_http_xslt_filter_loc_conf_t *conf; conf = ngx_http_get_module_loc_conf(r, ngx_http_xslt_filter_module); sheet = conf->sheets.elts; doc = ctx->doc; /* preallocate array for 4 params */ if (ngx_array_init(&ctx->params, r->pool, 4 * 2 + 1, sizeof(char *)) != NGX_OK) { xmlFreeDoc(doc); return NULL; } for (i = 0; i < conf->sheets.nelts; i++) { ctx->transform = xsltNewTransformContext(sheet[i].stylesheet, doc); if (ctx->transform == NULL) { xmlFreeDoc(doc); return NULL; } if (conf->params && ngx_http_xslt_params(r, ctx, conf->params, 0) != NGX_OK) { xsltFreeTransformContext(ctx->transform); xmlFreeDoc(doc); return NULL; } if (ngx_http_xslt_params(r, ctx, &sheet[i].params, 1) != NGX_OK) { xsltFreeTransformContext(ctx->transform); xmlFreeDoc(doc); return NULL; } res = xsltApplyStylesheetUser(sheet[i].stylesheet, doc, ctx->params.elts, NULL, NULL, ctx->transform); xsltFreeTransformContext(ctx->transform); xmlFreeDoc(doc); if (res == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "xsltApplyStylesheet() failed"); return NULL; } doc = res; /* reset array elements */ ctx->params.nelts = 0; } /* there must be at least one stylesheet */ if (r == r->main) { type = ngx_http_xslt_content_type(sheet[i - 1].stylesheet); } else { type = NULL; } encoding = ngx_http_xslt_encoding(sheet[i - 1].stylesheet); doc_type = doc->type; ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "xslt filter type: %d t:%s e:%s", doc_type, type ? type : (u_char *) "(null)", encoding ? encoding : (u_char *) "(null)"); rc = xsltSaveResultToString(&buf, &len, doc, sheet[i - 1].stylesheet); xmlFreeDoc(doc); if (rc != 0) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "xsltSaveResultToString() failed"); return NULL; } if (len == 0) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "xsltSaveResultToString() returned zero-length result"); return NULL; } b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { ngx_free(buf); return NULL; } b->pos = buf; b->last = buf + len; b->memory = 1; if (encoding) { r->headers_out.charset.len = ngx_strlen(encoding); r->headers_out.charset.data = encoding; } if (r != r->main) { return b; } b->last_buf = 1; if (type) { len = ngx_strlen(type); r->headers_out.content_type_len = len; r->headers_out.content_type.len = len; r->headers_out.content_type.data = type; } else if (doc_type == XML_HTML_DOCUMENT_NODE) { r->headers_out.content_type_len = sizeof("text/html") - 1; ngx_str_set(&r->headers_out.content_type, "text/html"); } r->headers_out.content_type_lowcase = NULL; return b; }
// 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; }
Datum xslt_process(PG_FUNCTION_ARGS) { #ifdef USE_LIBXSLT text *doct = PG_GETARG_TEXT_P(0); text *ssheet = PG_GETARG_TEXT_P(1); text *paramstr; const char **params; xsltStylesheetPtr stylesheet = NULL; xmlDocPtr doctree; xmlDocPtr restree; xmlDocPtr ssdoc = NULL; xmlChar *resstr; int resstat; int reslen; if (fcinfo->nargs == 3) { paramstr = PG_GETARG_TEXT_P(2); params = parse_params(paramstr); } else { /* No parameters */ params = (const char **) palloc(sizeof(char *)); params[0] = NULL; } /* Setup parser */ pgxml_parser_init(); /* Check to see if document is a file or a literal */ if (VARDATA(doct)[0] == '<') doctree = xmlParseMemory((char *) VARDATA(doct), VARSIZE(doct) - VARHDRSZ); else doctree = xmlParseFile(text_to_cstring(doct)); if (doctree == NULL) xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION, "error parsing XML document"); /* Same for stylesheet */ if (VARDATA(ssheet)[0] == '<') { ssdoc = xmlParseMemory((char *) VARDATA(ssheet), VARSIZE(ssheet) - VARHDRSZ); if (ssdoc == NULL) { xmlFreeDoc(doctree); xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION, "error parsing stylesheet as XML document"); } stylesheet = xsltParseStylesheetDoc(ssdoc); } else stylesheet = xsltParseStylesheetFile((xmlChar *) text_to_cstring(ssheet)); if (stylesheet == NULL) { xmlFreeDoc(doctree); xsltCleanupGlobals(); xml_ereport(ERROR, ERRCODE_EXTERNAL_ROUTINE_EXCEPTION, "failed to parse stylesheet"); } restree = xsltApplyStylesheet(stylesheet, doctree, params); resstat = xsltSaveResultToString(&resstr, &reslen, restree, stylesheet); xsltFreeStylesheet(stylesheet); xmlFreeDoc(restree); xmlFreeDoc(doctree); xsltCleanupGlobals(); if (resstat < 0) PG_RETURN_NULL(); PG_RETURN_TEXT_P(cstring_to_text_with_len((char *) resstr, reslen)); #else /* !USE_LIBXSLT */ ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("xslt_process() is not available without libxslt"))); PG_RETURN_NULL(); #endif /* USE_LIBXSLT */ }