예제 #1
0
static xsltStylesheetPtr 
savan_xpath_filter_mod_get_filter_template(
    const axutil_env_t *env,
    axis2_char_t *filter_template_path,
    xmlChar *filter)
{
    xsltStylesheetPtr xslt_template_xslt = NULL;
    xmlDocPtr xslt_template_xml = NULL;
    xmlChar* xpathExpr = NULL; 
    xmlXPathContextPtr xpathCtx = NULL;
    xmlXPathObjectPtr xpathObj = NULL;
	
    AXIS2_LOG_DEBUG(env->log, AXIS2_LOG_SI, "[savan] filter_template_path:%s", filter_template_path);

    xslt_template_xml = xmlParseFile(filter_template_path);
    xpathExpr = (xmlChar*)"//@select";
    xpathCtx = xmlXPathNewContext(xslt_template_xml);
    xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
    savan_xpath_filter_mod_update_filter_template(xpathObj->nodesetval, filter);

    xslt_template_xslt = xsltParseStylesheetDoc(xslt_template_xml);

	xmlXPathFreeObject(xpathObj);
	xmlXPathFreeContext(xpathCtx);

    return xslt_template_xslt;
}
예제 #2
0
/* call-seq:
 *    XSLT::Stylesheet.new(document) -> XSLT::Stylesheet
 *
 * Creates a new XSLT stylesheet based on the specified document.
 * For memory management reasons, a copy of the specified document
 * will be made, so its best to create a single copy of a stylesheet
 * and use it multiple times.
 *
 *  stylesheet_doc = XML::Document.file('stylesheet_file')
 *  stylesheet = XSLT::Stylesheet.new(stylesheet_doc)
 *
 */
static VALUE
ruby_xslt_stylesheet_initialize(VALUE self, VALUE document) {
  xmlDocPtr xdoc;
  xmlDocPtr xcopy;
  xsltStylesheetPtr xstylesheet;

  if (!rb_obj_is_kind_of(document, cXMLDocument))
    rb_raise(rb_eTypeError, "Must pass in an XML::Document instance.");

  /* NOTE!! Since the stylesheet own the specified document, the easiest
   * thing to do from a memory standpoint is too copy it and not expose
   * the copy to Ruby.  The other solution is expose a memory management
   * API on the document object for taking ownership of the document
   * and specifying when it has been freed.  Then the document class
   * has to be updated to always check and see if the document is
   * still valid.  That's all doable, but seems like a pain, so
   * just copy the document for now. */
  Data_Get_Struct(document, xmlDoc, xdoc);
  xcopy = xmlCopyDoc(xdoc, 1);
  xstylesheet = xsltParseStylesheetDoc(xcopy);
  xstylesheet->_private = (void *)self;
  DATA_PTR(self) = xstylesheet;

  /* Save a reference to the document as an attribute accessable to ruby */
  return self;
}
예제 #3
0
void c_XSLTProcessor::t_importstylesheet(const Object& stylesheet) {
  xmlDocPtr doc = nullptr;

  if (stylesheet.instanceof(c_DOMDocument::classof())) {
    c_DOMDocument *domdoc = stylesheet.getTyped<c_DOMDocument>();
    // This doc will be freed by xsltFreeStylesheet.
    doc = xmlCopyDoc((xmlDocPtr)domdoc->m_node, /*recursive*/ 1);
    if (doc == nullptr) {
      raise_error("Unable to import stylesheet");
    }
  } else if (stylesheet.instanceof(c_SimpleXMLElement::classof())) {
    c_SimpleXMLElement *elem = stylesheet.getTyped<c_SimpleXMLElement>();
    // This doc will be freed by xsltFreeStylesheet.
    doc = xmlNewDoc((const xmlChar*)"1.0");
    xmlNodePtr node = xmlCopyNode(elem->node, /*extended*/ 1);
    if (doc == nullptr || node == nullptr) {
      raise_error("Unable to import stylesheet");
    }
    xmlDocSetRootElement(doc, node);
  } else {
    raise_error("Object must be an instance of DOMDocument or "
                "SimpleXMLElement");
  }

  if (doc) {
    m_stylesheet = xsltParseStylesheetDoc(doc);
    if (m_stylesheet == nullptr) {
      raise_error("Unable to import stylesheet");
    }
  }
}
예제 #4
0
bool
XSLT::load(Inkscape::Extension::Extension *module)
{
    if (module->loaded()) { return true; }

    Inkscape::XML::Node *child_repr = module->get_repr()->firstChild();
    while (child_repr != NULL) {
        if (!strcmp(child_repr->name(), INKSCAPE_EXTENSION_NS "xslt")) {
            child_repr = child_repr->firstChild();
            while (child_repr != NULL) {
                if (!strcmp(child_repr->name(), INKSCAPE_EXTENSION_NS "file")) {
                    _filename = solve_reldir(child_repr);
                }
                child_repr = child_repr->next();
            }

            break;
        }
        child_repr = child_repr->next();
    }

    _parsedDoc = xmlParseFile(_filename.c_str());
    if (_parsedDoc == NULL) { return false; }

    _stylesheet = xsltParseStylesheetDoc(_parsedDoc);

    return true;
}
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);
}
예제 #6
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
			}
		}
	}
}
예제 #7
0
/*
 * call-seq:
 *   parse_stylesheet_doc(document)
 *
 * Parse a stylesheet from +document+.
 */
static VALUE parse_stylesheet_doc(VALUE klass, VALUE xmldocobj)
{
    xmlDocPtr xml ;
    xsltStylesheetPtr ss ;
    Data_Get_Struct(xmldocobj, xmlDoc, xml);
    exsltRegisterAll();
    ss = xsltParseStylesheetDoc(xmlCopyDoc(xml, 1)); /* 1 => recursive */
    return Data_Wrap_Struct(klass, NULL, dealloc, ss);
}
예제 #8
0
void XSLTransformer::initWithStylesheet(QString const &xsl)
{
    QByteArray xslData(xsl.toUtf8());
    xmlDocPtr xslDoc = xmlReadMemory(xslData.constData(), xslData.size(), 0, 0,
        XSLT_PARSE_OPTIONS);

    if (xslDoc == 0)
        throw std::runtime_error("XSLTransformer::initWithStylesheet: Could note parse stylesheet");

    d_xslPtr.reset(xsltParseStylesheetDoc(xslDoc));
}
예제 #9
0
XSLPrivate::XSLPrivate(const char *my_xsl)
{
    styleSheet = NULL;
    xmlSubstituteEntitiesDefault(1);
    xmlLoadExtDtdDefaultValue = 1;
    doc = xmlParseMemory(my_xsl, strlen(my_xsl));
    if (doc == NULL){
        log(L_WARN, "Can't parse XSLT");
        return;
    }
    styleSheet = xsltParseStylesheetDoc(doc);
}
예제 #10
0
파일: render.c 프로젝트: asl97/liferea
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;
}
예제 #11
0
파일: xdoc.C 프로젝트: viatsko/parser3
static void _transform(Request& r, MethodParams& params) {
	VXdoc& vdoc=GET_SELF(r, VXdoc);

	// params
	Array<const xmlChar*> transform_strings;
	const xmlChar** transform_params=0;
	if(params.count()>1)
		if(HashStringValue* hash=params.as_hash(1, "transform options")) {
			transform_params=new(UseGC) const xmlChar*[hash->count()*2+1];
			Add_xslt_param_info info={
				&r, 
				&transform_strings,
				transform_params
			};
			hash->for_each<Add_xslt_param_info*>(add_xslt_param, &info);
			transform_params[hash->count()*2]=0;
		}

	VXdoc* result;
	if(Value *vxdoc=params[0].as(VXDOC_TYPE)) { // stylesheet (xdoc)
		xmlDoc& stylesheetdoc=static_cast<VXdoc *>(vxdoc)->get_xmldoc();
		// compile xdoc stylesheet
		xsltStylesheet_auto_ptr stylesheet_ptr(xsltParseStylesheetDoc(&stylesheetdoc)); 
		if(xmlHaveGenericErrors())
			throw XmlException(0, r);
		if(!stylesheet_ptr.get())
			throw Exception("xml",
				0,
				"stylesheet failed to compile");
		// strange thing - xsltParseStylesheetDoc records document and destroys it in stylesheet destructor
		// we don't need that
		stylesheet_ptr->doc=0;

		// transform!
		result=&_transform(r, 0,
			vdoc, stylesheet_ptr.get(),
			transform_params);
	} else { // stylesheet (file name)
		// extablish stylesheet connection
		const String& stylesheet_filespec=
			r.absolute(params.as_string(0, "stylesheet must be file name (string) or DOM document (xdoc)"));
		Stylesheet_connection_ptr connection=stylesheet_manager->get_connection(stylesheet_filespec);

		// load and compile file to stylesheet [or get cached if any]
		// transform!
		result=&_transform(r, &stylesheet_filespec, vdoc, connection->stylesheet(),
			transform_params);
	}

	// write out result
	r.write_no_lang(*result);
}
예제 #12
0
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;
}
예제 #13
0
xsltStylesheetPtr XSLStyleSheet::compileStyleSheet()
{
    // FIXME: Hook up error reporting for the stylesheet compilation process.
    if (m_embedded)
        return xsltLoadStylesheetPI(document());

    // xsltParseStylesheetDoc makes the document part of the stylesheet
    // so we have to release our pointer to it.
    ASSERT(!m_stylesheetDocTaken);
    xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc);
    if (result)
        m_stylesheetDocTaken = true;
    return result;
}
예제 #14
0
 TImpl(const Stroka& style, const Stroka& base = "") {
     InitError();
     TxmlDocHolder sheetDoc(xmlParseMemory(~style, +style));
     if (!!base) {
         xmlNodeSetBase(sheetDoc->children, (xmlChar*)base.c_str());
     }
     if (!sheetDoc)
         ythrow yexception() << "cannot parse xml of xslt: " << ErrorMessage;
     Stylesheet.Reset(xsltParseStylesheetDoc(sheetDoc.Get()));
     if (!Stylesheet)
         ythrow yexception() << "cannot parse xslt: " << ErrorMessage;
     // sheetDoc - ownership transferred to Stylesheet
     sheetDoc.Release();
 }
예제 #15
0
/*
 * call-seq:
 *   parse_stylesheet_doc(document)
 *
 * Parse a stylesheet from +document+.
 */
static VALUE parse_stylesheet_doc(VALUE klass, VALUE xmldocobj)
{
    xmlDocPtr xml ;
    xsltStylesheetPtr ss ;
    Data_Get_Struct(xmldocobj, xmlDoc, xml);
    exsltRegisterAll();

    xsltSetGenericErrorFunc(NULL, xslt_generic_error_handler);

    ss = xsltParseStylesheetDoc(xmlCopyDoc(xml, 1)); /* 1 => recursive */

    xsltSetGenericErrorFunc(NULL, NULL);

    return Data_Wrap_Struct(klass, NULL, dealloc, ss);
}
예제 #16
0
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);
}
예제 #17
0
void KSXSLHandler::setXSL(const QString &document, QString style)
{
  styleSheet=0;
  xslDoc=0;

  QCString rawDocument=openXSL(document, style);
  xslDoc=xmlParseMemory(rawDocument, rawDocument.length());
  if(xslDoc)
  {
    styleSheet=xsltParseStylesheetDoc(xslDoc);
  }
  else
  {
    kdWarning() << "Wrong XSL format!" << endl;
    xmlFreeDoc(xslDoc);
    xslDoc=0;
  }
}
예제 #18
0
extern "C" xsltStylesheetPtr get_stylesheet(const char *name)
{
	// this needs to be done only once, but doesn't hurt to run every time
	xsltSetLoaderFunc(get_stylesheet_doc);

	// get main document:
	xmlDocPtr doc = get_stylesheet_doc((const xmlChar *)name, NULL, 0, NULL, XSLT_LOAD_START);
	if (!doc)
		return NULL;

	//	xsltSetGenericErrorFunc(stderr, NULL);
	xsltStylesheetPtr xslt = xsltParseStylesheetDoc(doc);
	if (!xslt) {
		xmlFreeDoc(doc);
		return NULL;
	}

	return xslt;
}
예제 #19
0
파일: parser.c 프로젝트: glejeune/ruby-xslt
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 );
}
예제 #20
0
void cepgdata2xmltv::LoadXSLT()
{
    if (pxsltStylesheet) return;
    xmlSetGenericErrorFunc(NULL,tvmGenericErrorFunc);
    xmlSubstituteEntitiesDefault (1);
    xmlLoadExtDtdDefaultValue = 1;
    xmlSetExternalEntityLoader(xmlMyExternalEntityLoader);
    exsltRegisterAll();

    if ((sxmlDoc = xmlReadMemory (xsl, sizeof(xsl), NULL,NULL,0)) != NULL)
    {
        pxsltStylesheet=xsltParseStylesheetDoc(sxmlDoc);
        if (!pxsltStylesheet)
        {
            esyslog("can't parse stylesheet");
            xmlFreeDoc (sxmlDoc);
            sxmlDoc=NULL;
        }
    }
}
xsltStylesheetPtr XSLStyleSheet::compileStyleSheet()
{
    // FIXME: Hook up error reporting for the stylesheet compilation process.
    if (m_embedded)
        return xsltLoadStylesheetPI(document());

    // Certain libxslt versions are corrupting the xmlDoc on compilation failures -
    // hence attempting to recompile after a failure is unsafe.
    if (m_compilationFailed)
        return 0;

    // xsltParseStylesheetDoc makes the document part of the stylesheet
    // so we have to release our pointer to it.
    ASSERT(!m_stylesheetDocTaken);
    xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc);
    if (result)
        m_stylesheetDocTaken = true;
    else
        m_compilationFailed = true;
    return result;
}
예제 #22
0
/**
 * Transform a document and return it.
 * @param in	document to transform.
 * @return		transformed document.
 */
Document *XSLTransform::transformDocument(Document *in) throw(XSLException) {
	xsltInit();

	// prepare parameters
	const char **aparams = new const char *[params.count() * 2 + 1];
	ASSERT(aparams);
	int i = 0;
	for(genstruct::AssocList<string, string>::PairIterator iter(params); iter; iter++) {
		aparams[i] = new char[(*iter).fst.length() + 1];
		strcpy((char *)aparams[i], &(*iter).fst);
		i++;
		aparams[i] = new char[(*iter).snd.length() + 1];
		strcpy((char *)aparams[i], &(*iter).snd);
		i++;
	}
	aparams[params.count() * 2] = 0;

	// perform the transformation
	xsltSetGenericErrorFunc(this, handle_error);
	xmlDoc *new_doc = xmlCopyDoc(DOC(ss->getNode()), 1);
	xsltStylesheetPtr stylesheet = xsltParseStylesheetDoc(new_doc);
	if(!stylesheet)
		throw XSLException("can not compile stylesheet");
	xmlDoc *res = xsltApplyStylesheet(stylesheet, DOC(in->getNode()), aparams);

	// clean up
	for(int i = 0; aparams[i]; i++)
		delete [] aparams[i];
	delete [] aparams;
	xmlSetStructuredErrorFunc(0, 0);
	xsltFreeStylesheet(stylesheet);
	if(!res)
		throw XSLException("error during XSLT transformation");

	// return result
	return fact->makeDocument(res);
}
예제 #23
0
static void HHVM_METHOD(XSLTProcessor, importStylesheet,
                        const Object& stylesheet) {
  SYNC_VM_REGS_SCOPED();

  auto data = Native::data<XSLTProcessorData>(this_);
  xmlDocPtr doc = nullptr;

  if (stylesheet.instanceof(s_DOMDocument)) {
    auto domdoc = Native::data<DOMNode>(stylesheet);
    // This doc will be freed by xsltFreeStylesheet.
    doc = xmlCopyDoc((xmlDocPtr)domdoc->nodep(), /*recursive*/ 1);
    if (doc == nullptr) {
      raise_error("Unable to import stylesheet");
    }
  } else if (stylesheet.instanceof(c_SimpleXMLElement::classof())) {
    auto elem = cast<c_SimpleXMLElement>(stylesheet);
    // This doc will be freed by xsltFreeStylesheet.
    doc = xmlNewDoc((const xmlChar*)"1.0");
    xmlNodePtr node = xmlCopyNode(elem->nodep(), /*extended*/ 1);
    if (doc == nullptr || node == nullptr) {
      raise_error("Unable to import stylesheet");
    }
    xmlDocSetRootElement(doc, node);
  } else {
    raise_error("Object must be an instance of DOMDocument or "
                "SimpleXMLElement");
  }

  if (doc) {
    data->m_stylesheet = xsltParseStylesheetDoc(doc);
    if (data->m_stylesheet == nullptr) {
      xmlFreeDoc(doc);
      raise_error("Unable to import stylesheet");
    }
  }
}
예제 #24
0
파일: XSLTUtils.cpp 프로젝트: Elzevir/xbmc
bool XSLTUtils::SetStylesheet(const std::string& stylesheet)
{
  if (m_xsltStylesheet) {
    xsltFreeStylesheet(m_xsltStylesheet);
    m_xsltStylesheet = NULL;
  }

  m_xmlStylesheet = xmlParseMemory(stylesheet.c_str(), stylesheet.size());
  if (!m_xmlStylesheet)
  {
    CLog::Log(LOGDEBUG, "could not xmlParseMemory stylesheetdoc");
    return false;
  }

  m_xsltStylesheet = xsltParseStylesheetDoc(m_xmlStylesheet);
  if (!m_xsltStylesheet) {
    CLog::Log(LOGDEBUG, "could not parse stylesheetdoc");
    xmlFree(m_xmlStylesheet);
    m_xmlStylesheet = NULL;
    return false;
  }
  
  return true;
}
예제 #25
0
/*
 * call-seq:
 *   parse_stylesheet_doc(document)
 *
 * Parse a stylesheet from +document+.
 */
static VALUE parse_stylesheet_doc(VALUE klass, VALUE xmldocobj)
{
    xmlDocPtr xml, xml_cpy;
    VALUE errstr, exception;
    xsltStylesheetPtr ss ;
    Data_Get_Struct(xmldocobj, xmlDoc, xml);
    exsltRegisterAll();

    errstr = rb_str_new(0, 0);
    xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler);

    xml_cpy = xmlCopyDoc(xml, 1); /* 1 => recursive */
    ss = xsltParseStylesheetDoc(xml_cpy);

    xsltSetGenericErrorFunc(NULL, NULL);

    if (!ss) {
	xmlFreeDoc(xml_cpy);
	exception = rb_exc_new3(rb_eRuntimeError, errstr);
	rb_exc_raise(exception);
    }

    return Nokogiri_wrap_xslt_stylesheet(ss);
}
예제 #26
0
static void *construct_xslt(const xmlNode *ptr,
                            const char *path, WRBUF wr_error)
{
    struct _xmlAttr *attr;
    const char *stylesheet = 0;
    struct xslt_info *info = 0;
    NMEM nmem = 0;
    int max_parms = 10;
    int no_parms = 0;

    if (strcmp((const char *) ptr->name, "xslt"))
        return 0;

    for (attr = ptr->properties; attr; attr = attr->next)
    {
        if (!xmlStrcmp(attr->name, BAD_CAST "stylesheet") &&
            attr->children && attr->children->type == XML_TEXT_NODE)
            stylesheet = (const char *) attr->children->content;
        else
        {
            wrbuf_printf(wr_error, "Bad attribute '%s'"
                         "Expected stylesheet.", attr->name);
            return 0;
        }
    }
    nmem = nmem_create();
    info = nmem_malloc(nmem, sizeof(*info));
    info->nmem = nmem;
    info->xsl_parms = nmem_malloc(
        nmem, (2 * max_parms + 1) * sizeof(*info->xsl_parms));

    for (ptr = ptr->children; ptr; ptr = ptr->next)
    {
        const char *name = 0;
        const char *value = 0;
        char *qvalue = 0;
        if (ptr->type != XML_ELEMENT_NODE)
            continue;
        if (strcmp((const char *) ptr->name, "param"))
        {
            wrbuf_printf(wr_error, "Bad element '%s'"
                         "Expected param.", ptr->name);
            nmem_destroy(nmem);
            return 0;
        }
        for (attr = ptr->properties; attr; attr = attr->next)
        {
            if (!xmlStrcmp(attr->name, BAD_CAST "name") &&
                attr->children && attr->children->type == XML_TEXT_NODE)
                name = (const char *) attr->children->content;
            else if (!xmlStrcmp(attr->name, BAD_CAST "value") &&
                attr->children && attr->children->type == XML_TEXT_NODE)
                value = (const char *) attr->children->content;
            else
            {
                wrbuf_printf(wr_error, "Bad attribute '%s'"
                             "Expected name or value.", attr->name);
                nmem_destroy(nmem);
                return 0;
            }
        }
        if (!name || !value)
        {
            wrbuf_printf(wr_error, "Missing attributes name or value");
            nmem_destroy(nmem);
            return 0;
        }
        if (no_parms >= max_parms)
        {
            wrbuf_printf(wr_error, "Too many parameters given");
            nmem_destroy(nmem);
            return 0;
        }

        qvalue = nmem_malloc(nmem, strlen(value) + 3);
        strcpy(qvalue, "\'");
        strcat(qvalue, value);
        strcat(qvalue, "\'");

        info->xsl_parms[2 * no_parms] = nmem_strdup(nmem, name);
        info->xsl_parms[2 * no_parms + 1] = qvalue;
        no_parms++;
    }
    info->xsl_parms[2 * no_parms] = 0;

    if (!stylesheet)
    {
        wrbuf_printf(wr_error, "Element <xslt>: "
                     "attribute 'stylesheet' expected");
        nmem_destroy(nmem);
    }
    else
    {
        char fullpath[1024];
        xsltStylesheetPtr xsp;
        if (!yaz_filepath_resolve(stylesheet, path, 0, fullpath))
        {
            wrbuf_printf(wr_error, "Element <xslt stylesheet=\"%s\"/>:"
                         " could not locate stylesheet '%s'",
                         stylesheet, stylesheet);
            if (path)
                wrbuf_printf(wr_error, " with path '%s'", path);

            nmem_destroy(nmem);
            return 0;
        }
        info->xsp_doc = xmlParseFile(fullpath);
        if (!info->xsp_doc)
        {
            wrbuf_printf(wr_error, "Element: <xslt stylesheet=\"%s\"/>:"
                         " xml parse failed: %s", stylesheet, fullpath);
            if (path)
                wrbuf_printf(wr_error, " with path '%s'", path);
            nmem_destroy(nmem);
            return 0;
        }
        /* need to copy this before passing it to the processor. It will
           be encapsulated in the xsp and destroyed by xsltFreeStylesheet */
        xsp = xsltParseStylesheetDoc(xmlCopyDoc(info->xsp_doc, 1));
        if (!xsp)
        {
            wrbuf_printf(wr_error, "Element: <xslt stylesheet=\"%s\"/>:"
                         " xslt parse failed: %s", stylesheet, fullpath);
            if (path)
                wrbuf_printf(wr_error, " with path '%s'", path);
            wrbuf_printf(wr_error, " ("
#if YAZ_HAVE_EXSLT

                         "EXSLT enabled"
#else
                         "EXSLT not supported"
#endif
                         ")");
            xmlFreeDoc(info->xsp_doc);
            nmem_destroy(info->nmem);
        }
        else
        {
            xsltFreeStylesheet(xsp);
            return info;
        }
    }
    return 0;
}
예제 #27
0
파일: xsltproc.c 프로젝트: way2joy/Sxslt
int
main(int argc, char **argv)
{
    int i;
    xsltStylesheetPtr cur = NULL;
    xmlDocPtr doc, style;

    if (argc <= 1) {
        usage(argv[0]);
        return (1);
    }

    xmlInitMemory();

    LIBXML_TEST_VERSION

    defaultLoader = xmlGetExternalEntityLoader();
    xmlLineNumbersDefault(1);

    if (novalid == 0)           /* TODO XML_DETECT_IDS | XML_COMPLETE_ATTRS */
        xmlLoadExtDtdDefaultValue = 6;
    else
        xmlLoadExtDtdDefaultValue = 0;
    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-"))
            break;

        if (argv[i][0] != '-')
            continue;
#ifdef LIBXML_DEBUG_ENABLED
        if ((!strcmp(argv[i], "-debug")) || (!strcmp(argv[i], "--debug"))) {
            debug++;
        } else
#endif
        if ((!strcmp(argv[i], "-v")) ||
                (!strcmp(argv[i], "-verbose")) ||
                (!strcmp(argv[i], "--verbose"))) {
            xsltSetGenericDebugFunc(stderr, NULL);
        } else if ((!strcmp(argv[i], "-o")) ||
                   (!strcmp(argv[i], "-output")) ||
                   (!strcmp(argv[i], "--output"))) {
            i++;
            output = argv[i++];
        } else if ((!strcmp(argv[i], "-V")) ||
                   (!strcmp(argv[i], "-version")) ||
                   (!strcmp(argv[i], "--version"))) {
            printf("Using libxml %s, libxslt %s and libexslt %s\n",
                   xmlParserVersion, xsltEngineVersion, exsltLibraryVersion);
            printf
    ("xsltproc was compiled against libxml %d, libxslt %d and libexslt %d\n",
                 LIBXML_VERSION, LIBXSLT_VERSION, LIBEXSLT_VERSION);
            printf("libxslt %d was compiled against libxml %d\n",
                   xsltLibxsltVersion, xsltLibxmlVersion);
            printf("libexslt %d was compiled against libxml %d\n",
                   exsltLibexsltVersion, exsltLibxmlVersion);
        } else if ((!strcmp(argv[i], "-repeat"))
                   || (!strcmp(argv[i], "--repeat"))) {
            if (repeat == 0)
                repeat = 20;
            else
                repeat = 100;
        } else if ((!strcmp(argv[i], "-novalid")) ||
                   (!strcmp(argv[i], "--novalid"))) {
            novalid++;
        } else if ((!strcmp(argv[i], "-noout")) ||
                   (!strcmp(argv[i], "--noout"))) {
            noout++;
#ifdef LIBXML_DOCB_ENABLED
        } else if ((!strcmp(argv[i], "-docbook")) ||
                   (!strcmp(argv[i], "--docbook"))) {
            docbook++;
#endif
#ifdef LIBXML_HTML_ENABLED
        } else if ((!strcmp(argv[i], "-html")) ||
                   (!strcmp(argv[i], "--html"))) {
            html++;
#endif
        } else if ((!strcmp(argv[i], "-timing")) ||
                   (!strcmp(argv[i], "--timing"))) {
            timing++;
        } else if ((!strcmp(argv[i], "-profile")) ||
                   (!strcmp(argv[i], "--profile"))) {
            profile++;
        } else if ((!strcmp(argv[i], "-norman")) ||
                   (!strcmp(argv[i], "--norman"))) {
            profile++;
        } else if ((!strcmp(argv[i], "-warnnet")) ||
                   (!strcmp(argv[i], "--warnnet"))) {
            xmlSetExternalEntityLoader(xsltNoNetExternalEntityLoader);
        } else if ((!strcmp(argv[i], "-nonet")) ||
                   (!strcmp(argv[i], "--nonet"))) {
            xmlSetExternalEntityLoader(xsltNoNetExternalEntityLoader);
            nonet = 1;
#ifdef LIBXML_CATALOG_ENABLED
        } else if ((!strcmp(argv[i], "-catalogs")) ||
                   (!strcmp(argv[i], "--catalogs"))) {
            const char *catalogs;

            catalogs = getenv("SGML_CATALOG_FILES");
            if (catalogs == NULL) {
                fprintf(stderr, "Variable $SGML_CATALOG_FILES not set\n");
            } else {
                xmlLoadCatalogs(catalogs);
            }
#endif
#ifdef LIBXML_XINCLUDE_ENABLED
        } else if ((!strcmp(argv[i], "-xinclude")) ||
                   (!strcmp(argv[i], "--xinclude"))) {
            xinclude++;
            xsltSetXIncludeDefault(1);
#endif
        } else if ((!strcmp(argv[i], "-param")) ||
                   (!strcmp(argv[i], "--param"))) {
            i++;
            params[nbparams++] = argv[i++];
            params[nbparams++] = argv[i];
            if (nbparams >= 16) {
                fprintf(stderr, "too many params\n");
                return (1);
            }
        } else if ((!strcmp(argv[i], "-maxdepth")) ||
                   (!strcmp(argv[i], "--maxdepth"))) {
            int value;

            i++;
            if (sscanf(argv[i], "%d", &value) == 1) {
                if (value > 0)
                    xsltMaxDepth = value;
            }
        } else if (!strcmp(argv[i], "--r")) {
	       startRAutomatically = 1;
               RstartupScript = strchr(argv[i],'=');
               continue;
        } else {
            fprintf(stderr, "Unknown option %s\n", argv[i]);
            usage(argv[0]);
            return (1);
        }
    }
    params[nbparams] = NULL;

    /*
     * Replace entities with their content.
     */
    xmlSubstituteEntitiesDefault(1);

    /*
     * Register the EXSLT extensions
     */
    exsltRegisterAll();
    registerRModule(0);
    if(startRAutomatically) {
        extern int RXSLT_internalSource(const char *fileName);
	int rargs = 1;
        const char *rargv[] = { "Sxsltproc" };
	Rf_initEmbeddedR(rargs, rargv);
	loadXSLPackage();           
        if(RstartupScript && RstartupScript[0])
	    RXSLT_internalSource(RstartupScript);
    }

    for (i = 1; i < argc; i++) {
        if ((!strcmp(argv[i], "-maxdepth")) ||
            (!strcmp(argv[i], "--maxdepth"))) {
            i++;
            continue;
        } else if ((!strcmp(argv[i], "-o")) ||
                   (!strcmp(argv[i], "-output")) ||
                   (!strcmp(argv[i], "--output"))) {
            i++;
	    continue;
	}
        if ((!strcmp(argv[i], "-param")) || (!strcmp(argv[i], "--param"))) {
            i += 2;
            continue;
        } else if(!strcmp(argv[i], "--r")) {
            continue;
	}
           
        if ((argv[i][0] != '-') || (strcmp(argv[i], "-") == 0)) {
            if (timing)
                gettimeofday(&begin, NULL);
	    style = xmlParseFile((const char *) argv[i]);
            if (timing) {
                long msec;

                gettimeofday(&end, NULL);
                msec = end.tv_sec - begin.tv_sec;
                msec *= 1000;
                msec += (end.tv_usec - begin.tv_usec) / 1000;
                fprintf(stderr, "Parsing stylesheet %s took %ld ms\n",
                        argv[i], msec);
            }
	    if (style == NULL) {
		fprintf(stderr,  "cannot parse %s\n", argv[i]);
		cur = NULL;
	    } else {
		cur = xsltLoadStylesheetPI(style);
		if (cur != NULL) {
		    /* it is an embedded stylesheet */
		    xsltProcess(style, cur, argv[i]);
		    xsltFreeStylesheet(cur);
		    exit(0);
		}
		cur = xsltParseStylesheetDoc(style);
		if (cur != NULL) {
		    if (cur->indent == 1)
			xmlIndentTreeOutput = 1;
		    else
			xmlIndentTreeOutput = 0;
		    i++;
		}
	    }
            break;

        }
    }

    /*
     * disable CDATA from being built in the document tree
     */
    xmlDefaultSAXHandlerInit();
    xmlDefaultSAXHandler.cdataBlock = NULL;

    if ((cur != NULL) && (cur->errors == 0)) {
        for (; i < argc; i++) {
	    doc = NULL;
            if (timing)
                gettimeofday(&begin, NULL);
#ifdef LIBXML_HTML_ENABLED
            if (html)
                doc = htmlParseFile(argv[i], NULL);
            else
#endif
#ifdef LIBXML_DOCB_ENABLED
            if (docbook)
                doc = docbParseFile(argv[i], NULL);
            else
#endif
                doc = xmlParseFile(argv[i]);
            if (doc == NULL) {
                fprintf(stderr, "unable to parse %s\n", argv[i]);
                continue;
            }
            if (timing) {
                long msec;

                gettimeofday(&end, NULL);
                msec = end.tv_sec - begin.tv_sec;
                msec *= 1000;
                msec += (end.tv_usec - begin.tv_usec) / 1000;
                fprintf(stderr, "Parsing document %s took %ld ms\n",
                        argv[i], msec);
            }
	    xsltProcess(doc, cur, argv[i]);
        }
        xsltFreeStylesheet(cur);
    }
#ifdef CAN_UNREGISTER_MODULES
    xsltUnregisterAllExtModules();
#endif
    xmlCleanupParser();
    xmlMemoryDump();
    return (0);
}
예제 #28
0
//    doc = xmlParseDoc(str);
//    xpath = xmlXPathNewContext(doc);
//    rez = xmlXPathEvalExpression("/root/mc",xpath);
//    if(rez != NULL){
//       puts("Resalt");
//      xmlChar * z = xmlNodeListGetString(doc, rez->nodesetval->nodeTab[0]->xmlChildrenNode, 1);
//      free(z);
//    }
//    xmlXPathFreeObject(rez);
//    xmlXPathFreeContext(xpath);
//    xmlFreeDoc(doc);
//}

static void xslt_class_compile_style(void * this, char * style){
	xmlDocPtr xlt_doc = xmlParseDoc(style);
	xsltStylesheetPtr cur = xsltParseStylesheetDoc(xlt_doc);
	((xslt_class*)this)->stylesheet = cur;
}

static void xslt_class_compile_style_file(void * this, char * styleFile){
	xsltStylesheetPtr cur = xsltParseStylesheetFile((const xmlChar *)styleFile);
	((xslt_class*)this)->stylesheet = cur;
}

static xmlChar * xslt_class_transform(void * this, char * xml){
	 xmlDocPtr doc, res;
			xmlChar *output;
			int len = 0 ;
			doc = xmlParseDoc(xml);
			res = xsltApplyStylesheet(((xslt_class*)this)->stylesheet, doc, ((xslt_class*)this)->params);
			xsltSaveResultToString(&output, &len, res, ((xslt_class*)this)->stylesheet);
예제 #29
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;
}
예제 #30
0
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;
}