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; }
/* * call-seq: * transform(document, params = []) * * Apply an XSLT stylesheet to an XML::Document. * +params+ is an array of strings used as XSLT parameters. * returns Nokogiri::XML::Document * * Example: * * doc = Nokogiri::XML(File.read(ARGV[0])) * xslt = Nokogiri::XSLT(File.read(ARGV[1])) * puts xslt.transform(doc, ['key', 'value']) * */ static VALUE transform(int argc, VALUE* argv, VALUE self) { VALUE xmldoc, paramobj ; xmlDocPtr xml ; xmlDocPtr result ; xsltStylesheetPtr ss ; const char** params ; int param_len, j ; rb_scan_args(argc, argv, "11", &xmldoc, ¶mobj); if (paramobj == Qnil) { paramobj = rb_ary_new2(0) ; } Data_Get_Struct(xmldoc, xmlDoc, xml); Data_Get_Struct(self, xsltStylesheet, ss); param_len = NUM2INT(rb_funcall(paramobj, rb_intern("length"), 0)); params = calloc((size_t)param_len+1, sizeof(char*)); for (j = 0 ; j < param_len ; j++) { VALUE entry = rb_ary_entry(paramobj, j); const char * ptr = StringValuePtr(entry); params[j] = ptr; } params[param_len] = 0 ; result = xsltApplyStylesheet(ss, xml, params); free(params); return Nokogiri_wrap_xml_document(0, result) ; }
/* * call-seq: * transform(document, params = []) * * Apply an XSLT stylesheet to an XML::Document. * +params+ is an array of strings used as XSLT parameters. * returns Nokogiri::XML::Document * * Example: * * doc = Nokogiri::XML(File.read(ARGV[0])) * xslt = Nokogiri::XSLT(File.read(ARGV[1])) * puts xslt.transform(doc, ['key', 'value']) * */ static VALUE transform(int argc, VALUE* argv, VALUE self) { VALUE xmldoc, paramobj ; xmlDocPtr xml ; xmlDocPtr result ; xsltStylesheetPtr ss ; const char** params ; int param_len, j ; rb_scan_args(argc, argv, "11", &xmldoc, ¶mobj); if (NIL_P(paramobj)) { paramobj = rb_ary_new2(0) ; } Data_Get_Struct(xmldoc, xmlDoc, xml); Data_Get_Struct(self, xsltStylesheet, ss); param_len = RARRAY_LEN(paramobj); params = calloc((size_t)param_len+1, sizeof(char*)); for (j = 0 ; j < param_len ; j++) { VALUE entry = rb_ary_entry(paramobj, j); const char * ptr = StringValuePtr(entry); params[j] = ptr; } params[param_len] = 0 ; result = xsltApplyStylesheet(ss, xml, params); free(params); if (!result) rb_raise(rb_eRuntimeError, "could not perform xslt transform on document"); return Nokogiri_wrap_xml_document(0, result) ; }
QString XSL::process(const QString &my_xml) { QString my_xsl; /* Petr Cimprich, Sablot developer: is predefined in HTML but not in XML ... use Unicode numerical entity instead:  */ my_xsl = quote_nbsp(my_xml); xmlDocPtr doc = xmlParseMemory(my_xsl.toUtf8(), my_xsl.toUtf8().length()); if (doc == NULL){ string s; s = static_cast<string>(my_xsl.toLocal8Bit()); log(L_WARN, "Parse XML error: %s", s.c_str()); return QString::null; } const char *params[1]; params[0] = NULL; xmlDocPtr res = xsltApplyStylesheet(d->styleSheet, doc, params); if (res == NULL){ log(L_WARN, "Apply stylesheet errror"); xmlFreeDoc(doc); return QString::null; } xmlFreeDoc(doc); xmlOutputBufferPtr buf = xmlAllocOutputBuffer(NULL); xsltSaveResultTo(buf, res, d->styleSheet); xmlFreeDoc(res); QString result = QString::fromUtf8((char*)(buf->buffer->content)); xmlOutputBufferClose(buf);; 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; }
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; }
DocumentImpl* XSLTProcessorImpl::transformDocument(DocumentImpl* doc) { // FIXME: Right now we assume |doc| is unparsed, but if it has been parsed we will need to serialize it // and then feed that resulting source to libxslt. m_resultOutput = ""; if (!m_stylesheet || !m_stylesheet->document()) return 0; globalSheet = m_stylesheet; xsltSetLoaderFunc(stylesheetLoadFunc); xsltStylesheetPtr sheet = m_stylesheet->compileStyleSheet(); globalSheet = 0; xsltSetLoaderFunc(0); if (!sheet) return 0; m_stylesheet->clearDocuments(); // Get the parsed source document. xmlDocPtr sourceDoc = (xmlDocPtr)doc->transformSource(); xmlDocPtr resultDoc = xsltApplyStylesheet(sheet, sourceDoc, NULL); DocumentImpl* result = documentFromXMLDocPtr(resultDoc, sheet); xsltFreeStylesheet(sheet); return result; }
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); }
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; }
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; }
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); }
/** * Write the transformed xml document out to a file descriptor. * @param xml The xml document * @param xsl The xml stylesheet * @param params The transform parameters * @param fd The source xml input descriptor * @return @c TRUE if successful, @c FALSE if an error occurs. * @ingroup EXML_XSLT_Group */ int exml_transform_fd_write( EXML *xml, EXML_XSL *xsl, const char *params[], int fd ) { int ret; xmlDocPtr res, doc; CHECK_PARAM_POINTER_RETURN("xml", xml, FALSE); CHECK_PARAM_POINTER_RETURN("xsl", xsl, FALSE); exml_doc_write(xml, &doc); res = xsltApplyStylesheet(xsl->cur, doc, params); xmlFreeDoc(doc); if( !res ) { return FALSE; } ret = xsltSaveResultToFd(fd, res, xsl->cur); xmlFreeDoc(res); xsltCleanupGlobals(); if( ret < 0 ) return FALSE; return TRUE; }
static xmlDoc *test_xslt_transforms(xmlDoc *doc, GError **error) { struct xslt_files *info = xslt_files; xmlDoc *transformed; xsltStylesheetPtr xslt = NULL; xmlNode *root_element = xmlDocGetRootElement(doc); char *attribute; while ((info->root) && (strcasecmp(root_element->name, info->root) != 0)) { info++; } if (info->root) { attribute = xmlGetProp(xmlFirstElementChild(root_element), "name"); if (attribute) { if (strcasecmp(attribute, "subsurface") == 0) { free((void *)attribute); return doc; } free((void *)attribute); } xmlSubstituteEntitiesDefault(1); xslt = get_stylesheet(info->file); if (xslt == NULL) { parser_error(error, _("Can't open stylesheet (%s)/%s"), xslt_path, info->file); return doc; } transformed = xsltApplyStylesheet(xslt, doc, NULL); xmlFreeDoc(doc); xsltFreeStylesheet(xslt); return transformed; } return doc; }
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()); }
void Transform(const TxmlDocHolder& srcDoc, TBuffer& dest, const TXslParams& params) { //xmlXIncludeProcessFlags(srcDoc.Get(), XSLT_PARSE_OPTIONS); if (!srcDoc) ythrow yexception() << "source xml is not valid: " << ErrorMessage; TxmlDocHolder res(xsltApplyStylesheet(Stylesheet.Get(), srcDoc.Get(), ~TParamsArray(params).Array)); // no params ENSURE(!!res, "Failed to apply xslt!"); SaveResult(res.Get(), Stylesheet.Get(), dest); }
int export_dives_xslt(const char *filename, const bool selected, const int units, const char *export_xslt) { FILE *f; struct membuffer buf = { 0 }; xmlDoc *doc; xsltStylesheetPtr xslt = NULL; xmlDoc *transformed; int res = 0; char *params[3]; int pnr = 0; char unitstr[3]; if (verbose) fprintf(stderr, "export_dives_xslt with stylesheet %s\n", export_xslt); if (!filename) return report_error("No filename for export"); /* Save XML to file and convert it into a memory buffer */ save_dives_buffer(&buf, selected); /* * Parse the memory buffer into XML document and * transform it to selected export format, finally dumping * the XML into a character buffer. */ doc = xmlReadMemory(buf.buffer, buf.len, "divelog", NULL, 0); free_buffer(&buf); if (!doc) return report_error("Failed to read XML memory"); /* Convert to export format */ xslt = get_stylesheet(export_xslt); if (!xslt) return report_error("Failed to open export conversion stylesheet"); snprintf(unitstr, 3, "%d", units); params[pnr++] = "units"; params[pnr++] = unitstr; params[pnr++] = NULL; transformed = xsltApplyStylesheet(xslt, doc, (const char **)params); xmlFreeDoc(doc); /* Write the transformed export to file */ f = subsurface_fopen(filename, "w"); if (f) { xsltSaveResultToFile(f, transformed, xslt); fclose(f); /* Check write errors? */ } else { res = report_error("Failed to open %s for writing (%s)", filename, strerror(errno)); } xsltFreeStylesheet(xslt); xmlFreeDoc(transformed); return res; }
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"; }
QString KSXSLHandler::parse(QString xmlString) { //check if the message is allready a HTML if(xmlString.find("<?xml version='1.0' encoding='UTF-8'?>")==-1) { return xmlString; } QStringList temp=KSData::instance()->getPartOfSpeech(); for(QStringList::Iterator count=temp.begin();count!=temp.end();count++) { xmlString.replace("<type>"+QString::number(KSData::instance()->getPartOfSpeechId(*count))+"</type>", "<type>"+*count+"</type>"); } QCString xmlCString=xmlString.utf8(); QString result; xmlDocPtr xmlDoc=xmlParseMemory(xmlCString, xmlCString.length()); if(xmlDoc) { if(styleSheet) { static QCString appPath( QString::fromLatin1("\"%1\"").arg( KApplication::kApplication()->dirs()->findDirs("appdata", QString::fromLatin1("styles/data") ).front() ).utf8() ); static const char* params[3] = { "appdata", appPath, NULL }; xmlDocPtr xmlResult=xsltApplyStylesheet(styleSheet, xmlDoc, params); if(xmlResult) { xmlChar *temp; int size; xmlDocDumpMemory(xmlResult, &temp, &size); result=QString::fromUtf8(QCString((char *)temp, size+1)); xmlFree(temp); xmlFreeDoc(xmlResult); } else { kdWarning() << "There is no phrase." << endl; } } else { kdWarning() << "No stylesheet loaded." << endl; } } else { kdWarning() << "Wrong XML format." << endl; } xmlFreeDoc(xmlDoc); xmlDoc=0; return result; }
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; }
int normalize_record_transform(normalize_record_t nt, xmlDoc **doc, const char **parms) { if (nt) { struct normalize_step *m; for (m = nt->steps; m; m = m->next) { xmlNodePtr root = 0; xmlDoc *ndoc; if (m->stylesheet) ndoc = xsltApplyStylesheet(m->stylesheet, *doc, parms); else if (m->stylesheet2) ndoc = xsltApplyStylesheet(m->stylesheet2, *doc, parms); else if (m->marcmap) ndoc = marcmap_apply(m->marcmap, *doc); else ndoc = 0; xmlFreeDoc(*doc); *doc = 0; if (ndoc) root = xmlDocGetRootElement(ndoc); if (ndoc && root && root->children) *doc = ndoc; else { if (!ndoc) yaz_log(YLOG_WARN, "XSLT produced no document"); else if (!root) yaz_log(YLOG_WARN, "XSLT produced XML with no root node"); else if (!root->children) yaz_log(YLOG_WARN, "XSLT produced XML with no root children nodes"); if (ndoc) xmlFreeDoc(ndoc); return -1; } } } return 0; }
/* * call-seq: * transform(document, params = []) * * Apply an XSLT stylesheet to an XML::Document. * +params+ is an array of strings used as XSLT parameters. * returns Nokogiri::XML::Document * * Example: * * doc = Nokogiri::XML(File.read(ARGV[0])) * xslt = Nokogiri::XSLT(File.read(ARGV[1])) * puts xslt.transform(doc, ['key', 'value']) * */ static VALUE transform(int argc, VALUE* argv, VALUE self) { VALUE xmldoc, paramobj, errstr, exception ; xmlDocPtr xml ; xmlDocPtr result ; nokogiriXsltStylesheetTuple *wrapper; const char** params ; long param_len, j ; int parse_error_occurred ; rb_scan_args(argc, argv, "11", &xmldoc, ¶mobj); if (NIL_P(paramobj)) { paramobj = rb_ary_new2(0L) ; } if (!rb_obj_is_kind_of(xmldoc, cNokogiriXmlDocument)) rb_raise(rb_eArgError, "argument must be a Nokogiri::XML::Document"); /* handle hashes as arguments. */ if(T_HASH == TYPE(paramobj)) { paramobj = rb_funcall(paramobj, rb_intern("to_a"), 0); paramobj = rb_funcall(paramobj, rb_intern("flatten"), 0); } Check_Type(paramobj, T_ARRAY); Data_Get_Struct(xmldoc, xmlDoc, xml); Data_Get_Struct(self, nokogiriXsltStylesheetTuple, wrapper); param_len = RARRAY_LEN(paramobj); params = calloc((size_t)param_len+1, sizeof(char*)); for (j = 0 ; j < param_len ; j++) { VALUE entry = rb_ary_entry(paramobj, j); const char * ptr = StringValuePtr(entry); params[j] = ptr; } params[param_len] = 0 ; errstr = rb_str_new(0, 0); xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler); xmlSetGenericErrorFunc(NULL, (xmlGenericErrorFunc)&swallow_superfluous_xml_errors); result = xsltApplyStylesheet(wrapper->ss, xml, params); free(params); xsltSetGenericErrorFunc(NULL, NULL); xmlSetGenericErrorFunc(NULL, NULL); parse_error_occurred = (Qfalse == rb_funcall(errstr, rb_intern("empty?"), 0)); if (parse_error_occurred) { exception = rb_exc_new3(rb_eRuntimeError, errstr); rb_exc_raise(exception); } return Nokogiri_wrap_xml_document((VALUE)0, result) ; }
/********************************************************************** 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 */
clish_xmldoc_t *clish_xslt_apply(clish_xmldoc_t *xmldoc, clish_xslt_t *stylesheet) { xmlDoc *doc = xmldoc_to_doc(xmldoc); xsltStylesheetPtr cur = xslt_to_xsltStylesheet(stylesheet); xmlDoc *res; if (!doc || !cur) return doc_to_xmldoc(NULL); res = xsltApplyStylesheet(cur, doc, NULL); return doc_to_xmldoc(res); }
/** * Apply stylesheet to doc and return the result */ xmlDocPtr CXSLTransform::Transform(xmlDocPtr doc) { ASSERT(doc); CWaitCursor wait; if (m_Style) { m_Result = xsltApplyStylesheet(m_Style, doc, NULL); } else { // No style -> return the doc m_Result = doc; } return m_Result; }
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; }
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; }
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, ¶ms); xsltSaveResultToFilename(outputfile.c_str(), result, stylesheet, 0); xmlFreeDoc(doc); xmlFreeDoc(result); xsltFreeStylesheet(stylesheet); }
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; }
/** * 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; }
void XSLT::save(Inkscape::Extension::Output */*module*/, SPDocument *doc, gchar const *filename) { /* TODO: Should we assume filename to be in utf8 or to be a raw filename? * See JavaFXOutput::save for discussion. */ g_return_if_fail(doc != NULL); g_return_if_fail(filename != NULL); Inkscape::XML::Node *repr = doc->getReprRoot(); std::string tempfilename_out; int tempfd_out = 0; try { tempfd_out = Inkscape::IO::file_open_tmp(tempfilename_out, "ink_ext_XXXXXX"); } catch (...) { /// \todo Popup dialog here return; } if (!sp_repr_save_rebased_file(repr->document(), tempfilename_out.c_str(), SP_SVG_NS_URI, doc->getBase(), filename)) { throw Inkscape::Extension::Output::save_failed(); } xmlDocPtr svgdoc = xmlParseFile(tempfilename_out.c_str()); close(tempfd_out); if (svgdoc == NULL) { return; } const char * params[1]; params[0] = NULL; xmlDocPtr newdoc = xsltApplyStylesheet(_stylesheet, svgdoc, params); //xmlSaveFile(filename, newdoc); int success = xsltSaveResultToFilename(filename, newdoc, _stylesheet, 0); xmlFreeDoc(newdoc); xmlFreeDoc(svgdoc); xsltCleanupGlobals(); xmlCleanupParser(); if (success < 1) { throw Inkscape::Extension::Output::save_failed(); } return; }