Exemplo n.º 1
0
/**
 * xmlnode_to_pv:
 * @node: an xmlNode* object
 * @do_free: do we need to free the node after the conversion
 *
 * Return value: a newly allocated SV/PV or under.
 */
static SV*
xmlnode_to_pv(xmlNode *node, gboolean do_free)
{
	xmlOutputBufferPtr buf;
	SV *pestring = NULL;

	if (node == NULL) {
		return &PL_sv_undef;
	}

	buf = xmlAllocOutputBuffer(NULL);
	if (buf == NULL) {
		pestring = &PL_sv_undef;
	} else {
		xmlNodeDumpOutput(buf, NULL, node, 0, 1, NULL);
		xmlOutputBufferFlush(buf);
		if (buf->conv == NULL) {
			pestring = newSVpv((char*)buf->buffer->content, 0);
		} else {
			pestring = newSVpv((char*)buf->conv->content, 0);
		}
		xmlOutputBufferClose(buf);
	}
	if (do_free) {
		lasso_release_xml_node(node);
	}

	return pestring;
}
Exemplo n.º 2
0
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;
}
Exemplo n.º 3
0
extern "C" void DumpXMLString(xmlNodePtr node)
{
    xmlOutputBufferPtr buf = xmlOutputBufferCreateFile(stdout, nullptr);
    xmlNodeDumpOutput(buf, node->doc, node, 0, 0, nullptr);
    xmlOutputBufferClose(buf);
    fprintf(stdout, "\n\n");
}
Exemplo n.º 4
0
  void XMLNode::GetXML(std::string& out_xml_str, bool user_friendly) const {
    out_xml_str.resize(0);
    if (!node_) return;
    if (node_->type != XML_ELEMENT_NODE) return;
    xmlDocPtr doc = node_->doc;
    if (doc == NULL) return;
    // Printing non-root node omits namespaces defined at higher level.
    // So we need to create temporary namespace definitions and place them 
    // at node being printed
    std::map<xmlNsPtr,xmlNsPtr> extns;
    CollectExternalNamespaces(node_, extns);
    // It is easier to insert namespaces into final text. Hence 
    // allocating place for them.
    std::string ns_str;
    NamespacesToString(extns, ns_str);
    out_xml_str.append(ns_str.length(),' ');
/*
    xmlBufferPtr buf = xmlBufferCreate();
    xmlNodeDump(buf, doc, node_, 0, user_friendly ? 1 : 0);
    out_xml_str = (char*)(buf->content);
    xmlBufferFree(buf);
*/
    xmlOutputBufferPtr buf =
     xmlOutputBufferCreateIO(&write_to_string,&close_string,&out_xml_str,NULL);
    if(buf == NULL) return;
    xmlNodeDumpOutput(buf, doc, node_, 0, user_friendly ? 1 : 0, (const char*)(doc->encoding));
    xmlOutputBufferClose(buf);
    // Insert external namespaces into final string using allocated space
    InsertExternalNamespaces(out_xml_str, ns_str);
  }
Exemplo n.º 5
0
bool XMLWrapper::nodeDump(xmlNodePtr node, std::string &content, bool trim)
{
	content.clear();

	if (!mDocument) {
		return false;
	}

	if (!node) {
		return false;
	}

	bool result = false;

	xmlBufferPtr buffer = xmlBufferCreate();
	if (buffer) {
		xmlOutputBufferPtr outputBuffer = xmlOutputBufferCreateBuffer(buffer, NULL);
		if (outputBuffer) {
			xmlNodeDumpOutput(outputBuffer, mDocument, node, 0, 0, "UTF8");
			xmlOutputBufferClose(outputBuffer);
			outputBuffer = NULL;

			result = convertToString(buffer->content, content);

			if (result && trim) {
				trimString(content);
			}
		}
		xmlBufferFree(buffer);
		buffer = NULL;
	}

	return result;
}
Exemplo n.º 6
0
static gchar *
update_apply_xslt (updateJobPtr job)
{
	xsltStylesheetPtr	xslt = NULL;
	xmlOutputBufferPtr	buf;
	xmlDocPtr		srcDoc = NULL, resDoc = NULL;
	gchar			*output = NULL;

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

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

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

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

	if (srcDoc)
		xmlFreeDoc (srcDoc);
	if (resDoc)
		xmlFreeDoc (resDoc);
	if (xslt)
		xsltFreeStylesheet (xslt);
	
	return output;
}
Exemplo n.º 7
0
	xmlOutputBuffer_auto_ptr& operator=(const xmlOutputBuffer_auto_ptr& _Y) 
		{if (this != &_Y)
			{if (_Ptr != _Y.get())
				{if (_Owns && _Ptr)
					xmlOutputBufferClose(_Ptr);
				_Owns = _Y._Owns; }
			else if (_Y._Owns)
				_Owns = true;
			_Ptr = _Y.release(); }
		return (*this); }
Exemplo n.º 8
0
 void SaveResult(xmlDocPtr doc, xsltStylesheetPtr stylesheet, TBuffer& to) {
     xmlOutputBufferPtr buf = xmlAllocOutputBuffer(NULL); // NULL means UTF8
     xsltSaveResultTo(buf, doc, stylesheet);
     if (buf->conv != NULL) {
         to.Assign((const char*)buf->conv->content, buf->conv->use);
     } else {
         to.Assign((const char*)buf->buffer->content, buf->buffer->use);
     }
     xmlOutputBufferClose(buf);
 }
Exemplo n.º 9
0
c_XMLWriter::~c_XMLWriter() {
  if (m_ptr) {
    xmlFreeTextWriter(m_ptr);
  }
  if (m_output) {
    xmlBufferFree(m_output);
  }
  if (m_uri_output) {
    xmlOutputBufferClose(m_uri_output);
  }
}
Exemplo n.º 10
0
static VALUE rxml_node_to_s(int argc, VALUE *argv, VALUE self)
{
  VALUE result = Qnil;
  VALUE options = Qnil;
  xmlNodePtr xnode;
  xmlCharEncodingHandlerPtr encodingHandler;
  xmlOutputBufferPtr output;

  int level = 0;
  int indent = 1;
  const char *xencoding = "UTF-8";

  rb_scan_args(argc, argv, "01", &options);

  if (!NIL_P(options))
  {
    VALUE rencoding, rindent, rlevel;
    Check_Type(options, T_HASH);
    rencoding = rb_hash_aref(options, ID2SYM(rb_intern("encoding")));
    rindent = rb_hash_aref(options, ID2SYM(rb_intern("indent")));
    rlevel = rb_hash_aref(options, ID2SYM(rb_intern("level")));

    if (rindent == Qfalse)
      indent = 0;

    if (rlevel != Qnil)
      level = NUM2INT(rlevel);

    if (rencoding != Qnil)
    {
      xencoding = xmlGetCharEncodingName((xmlCharEncoding)NUM2INT(rencoding));
      if (!xencoding)
        rb_raise(rb_eArgError, "Unknown encoding value: %d", NUM2INT(rencoding));
    }
  }

  encodingHandler = xmlFindCharEncodingHandler(xencoding);
  output = xmlAllocOutputBuffer(encodingHandler);

  xnode = rxml_get_xnode(self);

  xmlNodeDumpOutput(output, xnode->doc, xnode, level, indent, xencoding);
  xmlOutputBufferFlush(output);

  if (output->conv)
    result = rxml_new_cstr((const char*) output->conv->content, xencoding);
  else
    result = rxml_new_cstr((const char*) output->buffer->content, xencoding);

  xmlOutputBufferClose(output);
  
  return result;
}
Exemplo n.º 11
0
    std::string NSXmlCanonicalizator::Execute(const std::string& sXml, int mode, bool withComments)
    {
        xmlDocPtr xmlDoc = xmlParseMemory((char*)sXml.c_str(), (int)sXml.length());

        CXmlBuffer bufferC14N;
        xmlOutputBufferPtr _buffer = xmlOutputBufferCreateIO((xmlOutputWriteCallback)buffer_xmlBufferIOWrite,
                                                             (xmlOutputCloseCallback)buffer_xmlBufferIOClose,
                                                             &bufferC14N,
                                                             NULL);

        xmlC14NExecute(xmlDoc, buffer_xmlC14NIsVisibleCallback, NULL, mode, NULL, withComments ? 1 : 0, _buffer);

        xmlOutputBufferClose(_buffer);

        return bufferC14N.builder.GetData();
    }
Exemplo n.º 12
0
/* {{{ internalSubset	string
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-Core-DocType-internalSubset
Since: DOM Level 2
*/
int dom_documenttype_internal_subset_read(dom_object *obj, zval *retval)
{
	xmlDtdPtr dtdptr = (xmlDtdPtr) dom_object_get_node(obj);
	xmlDtdPtr intsubset;

	if (dtdptr == NULL) {
		php_dom_throw_error(INVALID_STATE_ERR, 0);
		return FAILURE;
	}

	if (dtdptr->doc != NULL && ((intsubset = xmlGetIntSubset(dtdptr->doc)) != NULL)) {
		smart_str ret_buf = {0};
		xmlNodePtr cur = intsubset->children;

		while (cur != NULL) {
			xmlOutputBuffer *buff = xmlAllocOutputBuffer(NULL);

			if (buff != NULL) {
				xmlNodeDumpOutput (buff, NULL, cur, 0, 0, NULL);
				xmlOutputBufferFlush(buff);

#ifdef LIBXML2_NEW_BUFFER
				smart_str_appendl(&ret_buf, (const char *) xmlOutputBufferGetContent(buff), xmlOutputBufferGetSize(buff));
#else
				smart_str_appendl(&ret_buf, (char *) buff->buffer->content, buff->buffer->use);
#endif

				(void)xmlOutputBufferClose(buff);
			}

			cur = cur->next;
		}

		if (ret_buf.s) {
			smart_str_0(&ret_buf);
			ZVAL_NEW_STR(retval, ret_buf.s);
			return SUCCESS;
		}
	}

	ZVAL_NULL(retval);

	return SUCCESS;

}
Exemplo n.º 13
0
static void
ews_autodiscover_data_free (AutodiscoverData *data)
{
	if (data->cancellable_id > 0) {
		g_cancellable_disconnect (
			data->cancellable, data->cancellable_id);
		g_object_unref (data->cancellable);
	}

	/* soup_session_queue_message stole the references to data->msgs */
	xmlOutputBufferClose (data->buf);
	g_object_unref (data->session);

	g_free (data->as_url);
	g_free (data->oab_url);

	g_slice_free (AutodiscoverData, data);
}
Exemplo n.º 14
0
static gboolean
ews_client_autodiscover_data_free (gpointer user_data)
{
  AutodiscoverData *data = user_data;

  g_simple_async_result_complete_in_idle (data->res);

  if (data->cancellable_id > 0)
    {
      g_cancellable_disconnect (data->cancellable, data->cancellable_id);
      g_object_unref (data->cancellable);
    }

  /* soup_session_queue_message stole the references to data->msgs */
  xmlOutputBufferClose (data->buf);
  g_object_unref (data->res);
  g_object_unref (data->session);
  g_slice_free (AutodiscoverData, data);

  return G_SOURCE_REMOVE;
}
Exemplo n.º 15
0
/**
 * htmlNodeDumpFileFormat:
 * @out:  the FILE pointer
 * @doc:  the document
 * @cur:  the current node
 * @encoding: the document encoding
 * @format:  should formatting spaces been added
 *
 * Dump an HTML node, recursive behaviour,children are printed too.
 *
 * TODO: if encoding == NULL try to save in the doc encoding
 *
 * returns: the number of byte written or -1 in case of failure.
 */
int
htmlNodeDumpFileFormat(FILE *out, xmlDocPtr doc,
	               xmlNodePtr cur, const char *encoding, int format) {
    xmlOutputBufferPtr buf;
    xmlCharEncodingHandlerPtr handler = NULL;
    int ret;

    xmlInitParser();

    if (encoding != NULL) {
	xmlCharEncoding enc;

	enc = xmlParseCharEncoding(encoding);
	if (enc != XML_CHAR_ENCODING_UTF8) {
	    handler = xmlFindCharEncodingHandler(encoding);
	    if (handler == NULL)
		return(-1);
	}
    }

    /*
     * Fallback to HTML or ASCII when the encoding is unspecified
     */
    if (handler == NULL)
	handler = xmlFindCharEncodingHandler("HTML");
    if (handler == NULL)
	handler = xmlFindCharEncodingHandler("ascii");

    /* 
     * save the content to a temp buffer.
     */
    buf = xmlOutputBufferCreateFile(out, handler);
    if (buf == NULL) return(0);

    htmlNodeDumpFormatOutput(buf, doc, cur, encoding, format);

    ret = xmlOutputBufferClose(buf);
    return(ret);
}
Exemplo n.º 16
0
static bool saveResultToString(xmlDocPtr resultDoc, xsltStylesheetPtr sheet, String& resultString)
{
    xmlOutputBufferPtr outputBuf = xmlAllocOutputBuffer(0);
    if (!outputBuf)
        return false;

    Vector<UChar> resultVector;
    outputBuf->context = &resultVector;
    outputBuf->writecallback = writeToVector;

    int retval = xsltSaveResultTo(outputBuf, resultDoc, sheet);
    xmlOutputBufferClose(outputBuf);
    if (retval < 0)
        return false;

    // Workaround for <http://bugzilla.gnome.org/show_bug.cgi?id=495668>: libxslt appends an extra line feed to the result.
    if (resultVector.size() > 0 && resultVector[resultVector.size() - 1] == '\n')
        resultVector.removeLast();

    resultString = String::adopt(resultVector);

    return true;
}
Exemplo n.º 17
0
int xsltSaveResultToString(xmlChar **doc_txt_ptr, int * doc_txt_len, xmlDocPtr result, xsltStylesheetPtr style) {
    xmlOutputBufferPtr buf;

    *doc_txt_ptr = NULL;
    *doc_txt_len = 0;
    if (result->children == NULL)
	return(0);

	buf = xmlAllocOutputBuffer(NULL);

    if (buf == NULL)
		return(-1);
    xsltSaveResultTo(buf, result, style);
    if (buf->conv != NULL) {
		*doc_txt_len = buf->conv->use;
		*doc_txt_ptr = xmlStrndup(buf->conv->content, *doc_txt_len);
    } else {
		*doc_txt_len = buf->buffer->use;
		*doc_txt_ptr = xmlStrndup(buf->buffer->content, *doc_txt_len);
    }
    (void)xmlOutputBufferClose(buf);
    return 0;
}
Exemplo n.º 18
0
void
Server::sendResponse(Context *ctx, XmlDocSharedHelper doc) {
    sendHeaders(ctx);
    if (ctx->response()->suppressBody(ctx->request())) {
        return;
    } 

    xmlCharEncodingHandlerPtr encoder = NULL;
    const std::string &encoding = ctx->documentWriter()->outputEncoding();
    if (!encoding.empty() && 0 != strncasecmp(encoding.c_str(), "utf-8", sizeof("utf-8"))) {
        encoder = xmlFindCharEncodingHandler(encoding.c_str());
    }
    
    xmlOutputBufferPtr buf = xmlOutputBufferCreateIO(writeFunc, closeFunc, ctx, encoder);
    XmlUtils::throwUnless(NULL != buf);

    try {
        ctx->documentWriter()->write(ctx->response(), doc.get(), buf);
    }
    catch(const std::exception &e) {
        xmlOutputBufferClose(buf);
        throw e;
    }
}
Exemplo n.º 19
0
 void XMLNode::GetXML(std::string& out_xml_str, const std::string& encoding, bool user_friendly) const {
   out_xml_str.resize(0);
   if (!node_) return;
   if (node_->type != XML_ELEMENT_NODE) return;
   xmlDocPtr doc = node_->doc;
   if (doc == NULL) return;
   xmlCharEncodingHandlerPtr handler = NULL;
   handler = xmlFindCharEncodingHandler(encoding.c_str());
   if (handler == NULL) return;
   std::map<xmlNsPtr,xmlNsPtr> extns;
   CollectExternalNamespaces(node_, extns);
   std::string ns_str;
   NamespacesToString(extns, ns_str);
   out_xml_str.append(ns_str.length(),' ');
   //xmlOutputBufferPtr buf = xmlAllocOutputBuffer(handler);
   xmlOutputBufferPtr buf =
    xmlOutputBufferCreateIO(&write_to_string,&close_string,&out_xml_str,NULL);
   if(buf == NULL) return;
   xmlNodeDumpOutput(buf, doc, node_, 0, user_friendly ? 1 : 0, encoding.c_str());
   xmlOutputBufferFlush(buf);
   //out_xml_str = (char*)(buf->conv ? buf->conv->content : buf->buffer->content);
   xmlOutputBufferClose(buf);
   InsertExternalNamespaces(out_xml_str, ns_str);
 }
Exemplo n.º 20
0
static bool saveResultToString(xmlDocPtr resultDoc, xsltStylesheetPtr sheet, String& resultString)
{
    xmlOutputBufferPtr outputBuf = xmlAllocOutputBuffer(0);
    if (!outputBuf)
        return false;

    StringBuilder resultBuilder;
    outputBuf->context = &resultBuilder;
    outputBuf->writecallback = writeToStringBuilder;

    int retval = xsltSaveResultTo(outputBuf, resultDoc, sheet);
    xmlOutputBufferClose(outputBuf);
    if (retval < 0)
        return false;

    // Workaround for <http://bugzilla.gnome.org/show_bug.cgi?id=495668>:
    // libxslt appends an extra line feed to the result.
    if (resultBuilder.length() > 0 && resultBuilder[resultBuilder.length() - 1] == '\n')
        resultBuilder.resize(resultBuilder.length() - 1);

    resultString = resultBuilder.toString();

    return true;
}
Exemplo n.º 21
0
bool XmlWriter::Create(IOStream *output, XmlWriter **r) {
  if (!LibXmlInitialized) {
    Error(StringPieceFromLiteral("XmlWriter::Create(): call LibXmlInit first()"));
    return false;
  }
  if (!output)
    return false;

  xmlOutputBufferPtr output_buffer = xmlOutputBufferCreateIO(_writeCallback, _closeCallback, output, NULL);
  if (!output_buffer) {
    Error(StringPieceFromLiteral("XmlWriter::Create(): xmlOutputBufferCreateIO fails"));
    return false;
  }

  std::auto_ptr<XmlWriter> xml(new XmlWriter());
  xml->libxml_stuff.reset(new LibXmlStuff());

  /* NOTE: the xmlOutputBufferPtr parameter will be deallocated when the writer is closed (if the call succeed.) */
  xml->libxml_stuff->writer = xmlNewTextWriter(output_buffer);
  if (!xml->libxml_stuff->writer) {
    xmlOutputBufferClose(output_buffer);
    output_buffer = NULL;
    Error(StringPieceFromLiteral("XmlWriter::Create(): xmlNewTextWriter fails"));
    return false;
  }

  if (r) {
    xmlTextWriterSetIndent(xml->libxml_stuff->writer, 1);
    /*if (!xml->StartDocument(output)) {
     cpcl::Error(cpcl::StringPieceFromLiteral("XmlWriter::Create(): xmlTextWriterStartDocument fails"));
     return false;
     }*/
    *r = xml.release();
  }
  return true;
}
Exemplo n.º 22
0
/**
 * HTML整形
 */
const wxString ExtractBoardList::HtmlFormat(const wxString& html)
{
     wxString val;
     const wxCharBuffer& cb = html.utf8_str();

     htmlDocPtr docPtr = htmlReadMemory(cb.data(), ::strlen(cb.data()), "", "utf-8", HTML_PARSE_RECOVER);
     if (docPtr)
     {
	  // libxml2の***Ptrは何かの構造体のポインタ
	  xmlOutputBufferPtr buf = xmlOutputBufferCreateIO((xmlOutputWriteCallback)writeToWxString,
							   (xmlOutputCloseCallback)closeWxString,
							   &val, 0);
	  
	  htmlDocContentDumpOutput(buf,
				   docPtr, 
				   "utf-8");

	  xmlOutputBufferClose(buf);
	  xmlFreeDoc(docPtr);
     }
     xmlCleanupParser();

     return val;
}
Exemplo n.º 23
0
int xslt_SaveResultToBuf (refbuf_t **bptr, int *len, xmlDocPtr result, xsltStylesheetPtr style)
{
    xmlOutputBufferPtr buf;
    struct bufs x;

    if (result->children == NULL)
    {
        *bptr = NULL;
        *len = 0;
        return 0;
    }

    memset (&x, 0, sizeof (x));
    x.tail = &x.head;
    buf = xmlOutputBufferCreateIO (xslt_write_callback, NULL, &x, NULL);

    if (buf == NULL)
		return  -1;
    xsltSaveResultTo (buf, result, style);
    *bptr = x.head;
    *len = x.len;
    xmlOutputBufferClose(buf);
    return 0;
}
Exemplo n.º 24
0
Arquivo: snk.c Projeto: DIGImend/hidrd
static bool
hidrd_xml_snk_flush(hidrd_snk *snk)
{
    bool                result      = false;
    hidrd_xml_snk_inst *xml_snk     = (hidrd_xml_snk_inst *)snk;
    bool                valid;
    xmlBufferPtr        xml_buf     = NULL;
    xmlOutputBufferPtr  xml_out_buf = NULL;
    void               *new_buf;
    size_t              new_size;

    XML_ERR_FUNC_BACKUP_DECL;

    free(xml_snk->err);
    xml_snk->err = strdup("");

    XML_ERR_FUNC_SET(&xml_snk->err);

    /* Break any unfinished groups */
    if (!xml_snk_group_break_branch(snk))
        goto cleanup;

    /* Validate the document, if the schema is specified */
    if (*xml_snk->schema != '\0' &&
        (!xml_validate(&valid, xml_snk->doc, xml_snk->schema) || !valid))
        goto cleanup;

    /* Create an XML buffer */
    xml_buf = xmlBufferCreate();
    if (xml_buf == NULL)
        goto cleanup;

    /* Create an XML output buffer from the generic buffer */
    xml_out_buf = xmlOutputBufferCreateBuffer(xml_buf, NULL);
    if (xml_out_buf == NULL)
        goto cleanup;

    /* Format XML from the document */
    if (xmlSaveFormatFileTo(xml_out_buf, xml_snk->doc,
                            NULL, xml_snk->format) < 0)
        goto cleanup;
    /* xml_out_buf is closed by xmlSaveFormatFileTo */
    xml_out_buf = NULL;

    /* Retrieve resulting size */
    new_size = xmlBufferLength(xml_buf);

    /* If we have a location for the buffer pointer */
    if (snk->pbuf != NULL)
    {
        /* Retention and update the buffer */
        new_buf = realloc(*snk->pbuf, new_size);
        if (new_size > 0 && new_buf == NULL)
            XML_ERR_CLNP("failed to retention the output buffer");
        memcpy(new_buf, xmlBufferContent(xml_buf), new_size);
        /* Update the buffer pointer */
        *snk->pbuf = new_buf;
    }

    /* Output size */
    if (snk->psize != NULL)
        *snk->psize = new_size;

    result = true;

cleanup:

    if (xml_out_buf != NULL)
        xmlOutputBufferClose(xml_out_buf);

    if (xml_buf != NULL)
        xmlBufferFree(xml_buf);

    XML_ERR_FUNC_RESTORE;

    return result;
}
Exemplo n.º 25
0
static void Save(const SObject *object, const char *path, s_erc *error)
{
	int rc;
	SUtterance *utt = S_UTTERANCE(object);
	SDatasource *ds;
	xmlTextWriterPtr writer;
	xmlOutputBufferPtr out;
	const char * xsi = "http://www.w3.org/2001/XMLSchema-instance";


	S_CLR_ERR(error);
	ds = SFilesourceOpenFile(path, "wt", error);
	if (S_CHK_ERR(error, S_CONTERR,
		      "Save",
		      "Call to \"SFilesourceOpenFile\" failed"))
		return;

	out = xmlOutputBufferCreateIO(_ds_write,
				      _ds_close,
				      ds,
				      NULL);
	if (out == NULL)
	{
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlOutputBufferCreateIO\" failed");
		return;
	}
	writer = xmlNewTextWriter(out);
	if (writer == NULL)
	{
                xmlOutputBufferClose(out);
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlNewTextWriter\" failed");
		return;
	}

	/* Start Document */
	rc = xmlTextWriterStartDocument(writer, NULL, ENCODING, NULL);
	if (rc < 0) {
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlTextWriterStartDocument\" failed");
		goto s_write_utt_exit;
	}

	/* Write the maryxml namespace */
	rc = xmlTextWriterStartElement(writer, BAD_CAST "xml");
	if (rc < 0) {
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlTextWriterStartElement\" failed");
		goto s_write_utt_exit;
	}

	rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "xmlns:xsi", BAD_CAST xsi);
	if (rc < 0) {
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlTextWriterWriteAttribute\" failed");
		goto s_write_utt_exit;
	}

	rc = xmlTextWriterWriteAttribute(writer, BAD_CAST "version", BAD_CAST "0.5");
	if (rc < 0) {
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlTextWriterWriteAttribute\" failed");
		goto s_write_utt_exit;
	}


	// print labels
	/* get to the first syllable of the current word */
	const SItem* itrSegments = SRelationHead(SUtteranceGetRelation(utt, "Segment", error), error);
	if (S_CHK_ERR(error, S_CONTERR,
		      "Save",
		      "Call to \"SItemPathToItem\" failed"))
 		goto s_write_utt_exit;
	while (itrSegments != NULL)
	{
		/* get segment content */
		const char* label = SItemGetString(itrSegments, "hts_label", error);
		if (S_CHK_ERR(error, S_CONTERR,
			      "Save",
			      "Call to \"SItemGetName\" failed"))
			goto s_write_utt_exit;

		/* get next segment */
		itrSegments = SItemNext(itrSegments, error);
		if (S_CHK_ERR(error, S_CONTERR,
			      "Save",
			      "Call to \"SItemNext\" failed"))
			goto s_write_utt_exit;

		xmlTextWriterWriteElement(writer, BAD_CAST "label", BAD_CAST label);

	}

	/* Close the tag xml */
	rc = xmlTextWriterEndElement(writer);
	if (rc < 0)
	{
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlTextWriterEndDocument\" failed");
		goto s_write_utt_exit;
	}
	/* Close the document */
	rc = xmlTextWriterEndDocument(writer);
	if (rc < 0)
	{
		S_CTX_ERR(error, S_CONTERR,
			  "Save",
			  "Call to \"xmlTextWriterEndDocument\" failed");
		goto s_write_utt_exit;
	}
s_write_utt_exit:
        xmlFreeTextWriter(writer);
}
Exemplo n.º 26
0
int writeXmlAnswsetToFd(MwsAnswset* answset, int fd)
{
#ifdef TRACE_FUNC_CALLS
    LOG_TRACE_IN;
#endif

    xmlOutputBuffer* outPtr;
    xmlTextWriter*   writerPtr;
    size_t           qvarNr;
    int              ret;
    unsigned int     i;
    vector<MwsAnsw*>::iterator it;

    // Initializing values
    outPtr    = NULL;
    writerPtr = NULL;
    ret       = -1;
    qvarNr    = answset->qvarNames.size();


    if (answset == NULL)
    {
        fprintf(stderr, "NULL answset passed to writeXmlAnswsetToFd");
    }
    // Creating the xmlOutputBuffer
    else if ((outPtr = xmlOutputBufferCreateIO(fdXmlOutputWriteCallback, 
                                               NULL,
                                               &fd, 
                                               NULL))
            == NULL)
    {
        fprintf(stderr, "Error while creating the OutputBuffer\n");
    }
    // Creating the xmlTextWriter
    else if ((writerPtr = xmlNewTextWriter(outPtr))
            == NULL)
    {
        fprintf(stderr, "Error while creating the TextWriter\n");
    }
    else if ((ret = xmlTextWriterStartDocument(writerPtr, // xmlTextWriter
                                               NULL,      // XML version ("1.0")
                                               NULL,      // Encoding ("UTF-8")
                                               NULL))     // Standalone ("yes")
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterStartDocument\n");
    }
    // MWS timestamp comment
    else if ((ret = xmlTextWriterWriteComment(writerPtr,
                    BAD_CAST "MwsAnswset generated by " __MWSTIMESTAMP__ " "))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterStartDocument\n");
    }
    // MWS answset
    else if ((ret = xmlTextWriterStartElement(writerPtr, 
                    BAD_CAST MWSANSWSET_MAIN_NAME))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterStartElement\n");
    }
    // mws namespace
    else if ((ret = xmlTextWriterWriteAttribute(writerPtr,
                    BAD_CAST "xmlns:mws",
                    BAD_CAST "http://www.mathweb.org/mws/ns"))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterWriteAttribute\n");
    }
    // attribute size
    else if ((ret = xmlTextWriterWriteAttribute(writerPtr,
                    BAD_CAST "size",
                    BAD_CAST ToString(answset->answers.size()).c_str()))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterWriteAttribute\n");
    }
    // attribute total
    else if ((ret = xmlTextWriterWriteAttribute(writerPtr,
                    BAD_CAST "total",
                    BAD_CAST ToString(answset->total).c_str()))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterWriteAttribute\n");
    }
    else
    // Writing the answers
    {
        for (it  = answset->answers.begin();
             it != answset->answers.end();
             it++)
        {
            if ((ret = xmlTextWriterStartElement(writerPtr,
                        BAD_CAST MWSANSWSET_ANSW_NAME))
                    == -1)
            {
                fprintf(stderr, "Error at xmlTextWriterStartElement\n");
                break;
            }
            else if ((ret = xmlTextWriterWriteAttribute(writerPtr,
                        BAD_CAST MWSANSWSET_URI_NAME,
                        BAD_CAST (*it)->uri.c_str()))
                    == -1)
            {
                fprintf(stderr, "Error at xmlTextWriterWriteAttribute\n");
                break;
            }
            else if ((ret = xmlTextWriterWriteAttribute(writerPtr,
                        BAD_CAST MWSANSWSET_XPATH_NAME,
                        BAD_CAST (*it)->xpath.c_str()))
                    == -1)
            {
                fprintf(stderr, "Error at xmlTextWriterWriteAttribute\n");
                break;
            }
            else
            {
                // Writing the substitutions
                for (i = 0; i < qvarNr; i++)
                {
                    if ((ret = xmlTextWriterStartElement(writerPtr,
                                BAD_CAST MWSANSWSET_SUBSTPAIR_NAME))
                            == -1)
                    {
                        fprintf(stderr, "Error at xmlTextWriterStartElement\n");
                        break;
                    }
                    else if ((ret = xmlTextWriterWriteAttribute(writerPtr,
                                BAD_CAST "qvar",
                                BAD_CAST answset->qvarNames[i].c_str()))
                            == -1)
                    {
                        fprintf(stderr,
                                "Error at xmlTextWriterWriteAttribute\n");
                        break;
                    }
                    else if ((ret = xmlTextWriterWriteAttribute(writerPtr,
                                BAD_CAST "xpath",
                                BAD_CAST (*it)->subst.qvarXpaths[i].c_str()))
                            == -1)
                    {
                        fprintf(stderr,
                                "Error at xmlTextWriterWriteAttribute\n");
                        break;
                    }
                    else if ((ret = xmlTextWriterEndElement(writerPtr))
                            == -1)
                    {
                        fprintf(stderr, "Error at xmlTextWriterEndElement\n");
                        break;
                    }
                }
            }
            if (ret == -1)
            {
                fprintf(stderr, "Error while writing xml substpairs\n");
                break;
            }
            else if ((ret = xmlTextWriterEndElement(writerPtr))
                    == -1)
            {
                fprintf(stderr, "Error at xmlTextWriterEndElement\n");
                break;
            }
        }
    }
    if (ret == -1)
    {
        fprintf(stderr, "Error while writing xml answers\n");
    }
    else if ((ret = xmlTextWriterEndElement(writerPtr))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterEndElement\n");
    }
    // Closing the document
    else if ((ret = xmlTextWriterEndDocument(writerPtr))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterEndDocument\n");
    }
    // Flushing the buffer
    else if ((ret = xmlTextWriterFlush(writerPtr))
            == -1)
    {
        fprintf(stderr, "Error at xmlTextWriterFlush\n");
    }
    // Everything ok
    else
    {
        ret = 0;
    }

    // Cleaning data
    if (writerPtr)
    {
        // This also cleans the outPtr
        xmlFreeTextWriter(writerPtr);
    }
    else if (outPtr)
    {
        xmlOutputBufferClose(outPtr);
    }

#ifdef TRACE_FUNC_CALLS
    LOG_TRACE_OUT;
#endif

    return ret;
}
Exemplo n.º 27
0
	~xmlOutputBuffer_auto_ptr()
		{if (_Owns && _Ptr)
			xmlOutputBufferClose(_Ptr); }
Exemplo n.º 28
0
/**
 * xmlSecEncCtxXmlEncrypt:
 * @encCtx:             the pointer to <enc:EncryptedData/> processing context.
 * @tmpl:               the pointer to <enc:EncryptedData/> template node.
 * @node:               the pointer to node for encryption.
 *
 * Encrypts @node according to template @tmpl. If requested, @node is replaced
 * with result <enc:EncryptedData/> node.
 *
 * Returns: 0 on success or a negative value if an error occurs.
 */
int
xmlSecEncCtxXmlEncrypt(xmlSecEncCtxPtr encCtx, xmlNodePtr tmpl, xmlNodePtr node) {
    xmlOutputBufferPtr output;
    int ret;

    xmlSecAssert2(encCtx != NULL, -1);
    xmlSecAssert2(encCtx->result == NULL, -1);
    xmlSecAssert2(tmpl != NULL, -1);
    xmlSecAssert2(node != NULL, -1);
    xmlSecAssert2(node->doc != NULL, -1);

    /* initialize context and add ID atributes to the list of known ids */
    encCtx->operation = xmlSecTransformOperationEncrypt;
    xmlSecAddIDs(tmpl->doc, tmpl, xmlSecEncIds);

    /* read the template and set encryption method, key, etc. */
    ret = xmlSecEncCtxEncDataNodeRead(encCtx, tmpl);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecEncCtxEncDataNodeRead",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    ret = xmlSecTransformCtxPrepare(&(encCtx->transformCtx), xmlSecTransformDataTypeBin);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecTransformCtxPrepare",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    "type=bin");
        return(-1);
    }

    xmlSecAssert2(encCtx->transformCtx.first != NULL, -1);
    output = xmlSecTransformCreateOutputBuffer(encCtx->transformCtx.first,
             &(encCtx->transformCtx));
    if(output == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    xmlSecErrorsSafeString(xmlSecTransformGetName(encCtx->transformCtx.first)),
                    "xmlSecTransformCreateOutputBuffer",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    /* push data thru */
    if((encCtx->type != NULL) && xmlStrEqual(encCtx->type, xmlSecTypeEncElement)) {
        /* get the content of the node */
        xmlNodeDumpOutput(output, node->doc, node, 0, 0, NULL);
    } else if((encCtx->type != NULL) && xmlStrEqual(encCtx->type, xmlSecTypeEncContent)) {
        xmlNodePtr cur;

        /* get the content of the nodes childs */
        for(cur = node->children; cur != NULL; cur = cur->next) {
            xmlNodeDumpOutput(output, node->doc, cur, 0, 0, NULL);
        }
    } else {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    NULL,
                    XMLSEC_ERRORS_R_INVALID_TYPE,
                    "type=%s",
                    xmlSecErrorsSafeString(encCtx->type));
        xmlOutputBufferClose(output);
        return(-1);
    }

    /* close the buffer and flush everything */
    ret = xmlOutputBufferClose(output);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlOutputBufferClose",
                    XMLSEC_ERRORS_R_XML_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    encCtx->result = encCtx->transformCtx.result;
    xmlSecAssert2(encCtx->result != NULL, -1);

    ret = xmlSecEncCtxEncDataNodeWrite(encCtx);
    if(ret < 0) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "xmlSecEncCtxEncDataNodeWrite",
                    XMLSEC_ERRORS_R_XMLSEC_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        return(-1);
    }

    /* now we need to update our original document */
    if((encCtx->type != NULL) && xmlStrEqual(encCtx->type, xmlSecTypeEncElement)) {
        /* check if we need to return the replaced node */
        if((encCtx->flags & XMLSEC_ENC_RETURN_REPLACED_NODE) != 0) {
            ret = xmlSecReplaceNodeAndReturn(node, tmpl, &(encCtx->replacedNodeList));
            if(ret < 0) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            "xmlSecReplaceNode",
                            XMLSEC_ERRORS_R_XMLSEC_FAILED,
                            "node=%s",
                            xmlSecErrorsSafeString(xmlSecNodeGetName(node)));
                return(-1);
            }
        } else {
            ret = xmlSecReplaceNode(node, tmpl);
            if(ret < 0) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            "xmlSecReplaceNode",
                            XMLSEC_ERRORS_R_XMLSEC_FAILED,
                            "node=%s",
                            xmlSecErrorsSafeString(xmlSecNodeGetName(node)));
                return(-1);
            }
        }

        encCtx->resultReplaced = 1;
    } else if((encCtx->type != NULL) && xmlStrEqual(encCtx->type, xmlSecTypeEncContent)) {
        /* check if we need to return the replaced node */
        if((encCtx->flags & XMLSEC_ENC_RETURN_REPLACED_NODE) != 0) {
            ret = xmlSecReplaceContentAndReturn(node, tmpl, &(encCtx->replacedNodeList));
            if(ret < 0) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            "xmlSecReplaceContentAndReturn",
                            XMLSEC_ERRORS_R_XMLSEC_FAILED,
                            "node=%s",
                            xmlSecErrorsSafeString(xmlSecNodeGetName(node)));
                return(-1);
            }
        } else {
            ret = xmlSecReplaceContent(node, tmpl);
            if(ret < 0) {
                xmlSecError(XMLSEC_ERRORS_HERE,
                            NULL,
                            "xmlSecReplaceContent",
                            XMLSEC_ERRORS_R_XMLSEC_FAILED,
                            "node=%s",
                            xmlSecErrorsSafeString(xmlSecNodeGetName(node)));
                return(-1);
            }
        }

        encCtx->resultReplaced = 1;
    } else {
        /* we should've catached this error before */
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    NULL,
                    XMLSEC_ERRORS_R_INVALID_TYPE,
                    "type=%s",
                    xmlSecErrorsSafeString(encCtx->type));
        return(-1);
    }
    return(0);
}
Exemplo n.º 29
0
int MwsXmlResponseFormatter::writeData(const GenericAnswer* ans,
                                       FILE* output) const {
    const MwsAnswset& answerSet = *((const MwsAnswset*)ans);
    xmlOutputBuffer* outPtr;
    xmlTextWriter* writerPtr;
    size_t qvarNr;
    int ret;
    unsigned int i;
    LocalContext ctxt;

    // Initializing values
    outPtr = nullptr;
    writerPtr = nullptr;
    ret = -1;
    qvarNr = answerSet.qvarNames.size();
    ctxt.file = output;
    ctxt.total_bytes_written = 0;

    if ((outPtr = xmlOutputBufferCreateIO(fileXmlOutputWriteCallback, nullptr,
                                          &ctxt, nullptr)) ==
        nullptr) {
        PRINT_WARN("Error while creating the OutputBuffer\n");
    } else if ((writerPtr = xmlNewTextWriter(outPtr)) == nullptr) {
        PRINT_WARN("Error while creating the TextWriter\n");
    } else if ((ret =
                    xmlTextWriterStartDocument(writerPtr,  // xmlTextWriter
                                               nullptr,   // XML version ("1.0")
                                               nullptr,   // Encoding ("UTF-8")
                                               nullptr))  // Standalone ("yes")
               ==
               -1) {
        PRINT_WARN("Error at xmlTextWriterStartDocument\n");
    } else if ((ret = xmlTextWriterWriteComment(
                    writerPtr,
                    BAD_CAST "MwsAnswset generated by " MWS_BUILD)) ==
               -1) {
        PRINT_WARN("Error at xmlTextWriterStartDocument\n");
    } else if ((ret = xmlTextWriterStartElement(
                    writerPtr, BAD_CAST MWSANSWSET_MAIN_NAME)) ==
               -1) {
        PRINT_WARN("Error at xmlTextWriterStartElement\n");
    } else if ((ret = xmlTextWriterWriteAttribute(
                    writerPtr, BAD_CAST "xmlns:mws",
                    BAD_CAST "http://www.mathweb.org/mws/ns")) ==
               -1) {
        PRINT_WARN("Error at xmlTextWriterWriteAttribute\n");
    } else if ((ret = xmlTextWriterWriteAttribute(
                    writerPtr, BAD_CAST "size",
                    BAD_CAST std::to_string(answerSet.answers.size())
                        .c_str())) ==
               -1) {
        PRINT_WARN("Error at xmlTextWriterWriteAttribute\n");
    } else if ((ret = xmlTextWriterWriteAttribute(
                    writerPtr, BAD_CAST "total",
                    BAD_CAST std::to_string(answerSet.total).c_str())) ==
               -1) {
        PRINT_WARN("Error at xmlTextWriterWriteAttribute\n");
    } else {
        for (auto& answer : answerSet.answers) {
            if ((ret = xmlTextWriterStartElement(
                     writerPtr, BAD_CAST MWSANSWSET_ANSW_NAME)) ==
                -1) {
                PRINT_WARN("Error at xmlTextWriterStartElement\n");
                break;
            } else if ((ret = xmlTextWriterWriteAttribute(
                            writerPtr, BAD_CAST MWSANSWSET_URI_NAME,
                            BAD_CAST answer->uri.c_str())) ==
                       -1) {
                PRINT_WARN("Error at xmlTextWriterWriteAttribute\n");
                break;
            } else if ((ret = xmlTextWriterWriteAttribute(
                            writerPtr, BAD_CAST MWSANSWSET_XPATH_NAME,
                            BAD_CAST answer->xpath.c_str())) ==
                       -1) {
                PRINT_WARN("Error at xmlTextWriterWriteAttribute\n");
                break;
            } else {
                // Writing the substitutions
                for (i = 0; i < qvarNr; i++) {
                    string qvarXpath = answer->xpath + answerSet.qvarXpaths[i];
                    if ((ret = xmlTextWriterStartElement(
                             writerPtr, BAD_CAST MWSANSWSET_SUBSTPAIR_NAME)) ==
                        -1) {
                        PRINT_WARN("Error at xmlTextWriterStartElement\n");
                        break;
                    } else if ((ret = xmlTextWriterWriteAttribute(
                                    writerPtr, BAD_CAST "qvar",
                                    BAD_CAST answerSet.qvarNames[i].c_str())) ==
                               -1) {
                        PRINT_WARN("Error at xmlTextWriterWriteAttribute\n");
                        break;
                    } else if ((ret = xmlTextWriterWriteAttribute(
                                    writerPtr, BAD_CAST "xpath",
                                    BAD_CAST qvarXpath.c_str())) ==
                               -1) {
                        PRINT_WARN("Error at xmlTextWriterWriteAttribute\n");
                        break;
                    } else if ((ret = xmlTextWriterEndElement(writerPtr)) ==
                               -1) {
                        PRINT_WARN("Error at xmlTextWriterEndElement\n");
                        break;
                    }
                }
                // <data> ... </data>
                xmlTextWriterWriteElement(writerPtr, BAD_CAST "data",
                                          BAD_CAST answer->data.c_str());
            }
            if (ret == -1) {
                PRINT_WARN("Error while writing xml substpairs\n");
                break;
            } else if ((ret = xmlTextWriterEndElement(writerPtr)) == -1) {
                PRINT_WARN("Error at xmlTextWriterEndElement\n");
                break;
            }
        }
    }
    if (ret == -1) {
        PRINT_WARN("Error while writing xml answers\n");
    } else if ((ret = xmlTextWriterEndElement(writerPtr)) == -1) {
        PRINT_WARN("Error at xmlTextWriterEndElement\n");
    } else if ((ret = xmlTextWriterEndDocument(writerPtr)) == -1) {
        PRINT_WARN("Error at xmlTextWriterEndDocument\n");
    } else if ((ret = xmlTextWriterFlush(writerPtr)) == -1) {
        PRINT_WARN("Error at xmlTextWriterFlush\n");
    } else {
        ret = 0;
    }

    // Cleaning data
    if (writerPtr) {
        // This also cleans the outPtr
        xmlFreeTextWriter(writerPtr);
    } else if (outPtr) {
        xmlOutputBufferClose(outPtr);
    }

    if (ret == 0) {
        return ctxt.total_bytes_written;
    } else {
        return ret;
    }
}
Exemplo n.º 30
0
/**
 * htmlDocDumpMemory:
 * @cur:  the document
 * @mem:  OUT: the memory pointer
 * @size:  OUT: the memory length
 *
 * Dump an HTML document in memory and return the xmlChar * and it's size.
 * It's up to the caller to free the memory.
 */
void
htmlDocDumpMemory(xmlDocPtr cur, xmlChar**mem, int *size) {
    xmlOutputBufferPtr buf;
    xmlCharEncodingHandlerPtr handler = NULL;
    const char *encoding;

    xmlInitParser();

    if ((mem == NULL) || (size == NULL))
        return;
    if (cur == NULL) {
	*mem = NULL;
	*size = 0;
	return;
    }

    encoding = (const char *) htmlGetMetaEncoding(cur);

    if (encoding != NULL) {
	xmlCharEncoding enc;

	enc = xmlParseCharEncoding(encoding);
	if (enc != cur->charset) {
	    if (cur->charset != XML_CHAR_ENCODING_UTF8) {
		/*
		 * Not supported yet
		 */
		*mem = NULL;
		*size = 0;
		return;
	    }

	    handler = xmlFindCharEncodingHandler(encoding);
	    if (handler == NULL) {
		*mem = NULL;
		*size = 0;
		return;
	    }
	} else {
	    handler = xmlFindCharEncodingHandler(encoding);
	}
    }

    /*
     * Fallback to HTML or ASCII when the encoding is unspecified
     */
    if (handler == NULL)
	handler = xmlFindCharEncodingHandler("HTML");
    if (handler == NULL)
	handler = xmlFindCharEncodingHandler("ascii");

    buf = xmlAllocOutputBuffer(handler);
    if (buf == NULL) {
	*mem = NULL;
	*size = 0;
	return;
    }

    htmlDocContentDumpOutput(buf, cur, NULL);
    xmlOutputBufferFlush(buf);
    if (buf->conv != NULL) {
	*size = buf->conv->use;
	*mem = xmlStrndup(buf->conv->content, *size);
    } else {
	*size = buf->buffer->use;
	*mem = xmlStrndup(buf->buffer->content, *size);
    }
    (void)xmlOutputBufferClose(buf);
}