Пример #1
0
TrackerConfig::TrackerConfig(const TrackerConfig& other)
{
    m_Doc = 0;
    if (other.m_Doc) {
        m_Doc = xmlCopyDoc(other.m_Doc, true);
        m_sFilename = other.m_sFilename;
        m_pRoot = xmlDocGetRootElement(m_Doc);
    }
}
Пример #2
0
bool cXmlDoc::read(xmlDocPtr doc) {
#ifdef DUMP
fprintf(stderr, "cXmlDoc::read (xmlDocPtr)\n");
fflush(stderr);
#endif
    Init();
    claimErrors();
    assignDoc(xmlCopyDoc(doc, 1));
    releaseErrors();
    return ok();
}
Пример #3
0
XMLWrapper &XMLWrapper::operator=(const XMLWrapper &xml)
{
	cleanup();

	const xmlDocPtr document = xml.getDocument();
	if (document) {
		mDocument = xmlCopyDoc(document, 1);
	}

	return *this;
}
Пример #4
0
Document Document::clone(const Document& source)
{
	if (source._xmlDoc == nullptr)
	{
		// Nothing to clone, create an empty doc
		return Document(nullptr);
	}

	// Create a deep copy of the other doc
	return Document(xmlCopyDoc(source._xmlDoc, 1));
}
Пример #5
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;
}
Пример #6
0
Variant c_XSLTProcessor::t_transformtodoc(const Object& doc) {
  if (doc.instanceof(c_DOMNode::classof())) {
    c_DOMNode *domnode = doc.getTyped<c_DOMNode>();
    m_doc = xmlCopyDoc((xmlDocPtr)domnode->m_node, /*recursive*/ 1);

    c_DOMDocument *res = NEWOBJ(c_DOMDocument)();
    res->m_node = (xmlNodePtr)apply_stylesheet();
    res->m_owner = true;

    return res;
  }

  return false;
}
Пример #7
0
//---------------------------------------------------------------------------
xmlDocPtr UnknownPolicy::create_doc()
{
    xmlDocPtr doc = NULL;

    if (system_doc)
        doc = xmlCopyDoc(system_doc, 1);
    else
        doc = xmlParseFile(filename.c_str());
    if (!doc)
    {
        error = "Unknwn policy should be a valid XML";
        return NULL;
    }
    return doc;
}
Пример #8
0
static cache_entry* cache_entry_from_xdr_doc(xmlDocPtr doc)
{
    cache_entry* entry = heap_alloc(sizeof(cache_entry));
    xmlDocPtr new_doc = xmlCopyDoc(doc, 1);

    FIXME("XDR schema support not implemented\n");
    entry->type = SCHEMA_TYPE_XDR;
    entry->ref = 0;
    entry->schema = NULL;
    entry->doc = new_doc;
    xmldoc_init(entry->doc, &CLSID_DOMDocument30);
    xmldoc_add_ref(entry->doc);

    return entry;
}
Пример #9
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);
}
Пример #10
0
/*
 * call-seq:
 *  dup
 *
 * Copy this Document.  An optional depth may be passed in, but it defaults
 * to a deep copy.  0 is a shallow copy, 1 is a deep copy.
 */
static VALUE duplicate_node(int argc, VALUE *argv, VALUE self)
{
  xmlDocPtr doc, dup;
  VALUE level;

  if(rb_scan_args(argc, argv, "01", &level) == 0)
    level = INT2NUM((long)1);

  Data_Get_Struct(self, xmlDoc, doc);

  dup = xmlCopyDoc(doc, (int)NUM2INT(level));
  if(dup == NULL) return Qnil;

  dup->type = doc->type;
  return Nokogiri_wrap_xml_document(rb_obj_class(self), dup);
}
Пример #11
0
value
v2v_xml_copy_doc (value docv, value recursivev)
{
  CAMLparam2 (docv, recursivev);
  CAMLlocal1 (copyv);
  xmlDocPtr doc, copy;

  doc = Doc_val (docv);
  copy = xmlCopyDoc (doc, Bool_val (recursivev));
  if (copy == NULL)
    caml_invalid_argument ("copy_doc: failed to copy");

  copyv = caml_alloc_custom (&doc_custom_operations, sizeof (xmlDocPtr), 0, 1);
  Doc_val (copyv) = copy;

  CAMLreturn (copyv);
}
Пример #12
0
static Variant HHVM_METHOD(XSLTProcessor, transformToDoc,
                           const Object& doc) {
  auto data = Native::data<XSLTProcessorData>(this_);

  if (doc.instanceof(DOMNode::getClass())) {
    DOMNode *domnode = toDOMNode(doc.get());
    data->m_doc = xmlCopyDoc((xmlDocPtr)domnode->m_node, /*recursive*/ 1);

    ObjectData* ret = ObjectData::newInstance(DOMDocument::c_Class);
    DOMDocument* doc_data = Native::data<DOMDocument>(ret);
    doc_data->m_node = (xmlNodePtr)data->apply_stylesheet();
    doc_data->m_owner = true;

    return Object(ret);
  }

  return false;
}
Пример #13
0
/*
 * call-seq:
 *  dup
 *
 * Copy this Document.  An optional depth may be passed in, but it defaults
 * to a deep copy.  0 is a shallow copy, 1 is a deep copy.
 */
static VALUE duplicate_node(int argc, VALUE *argv, VALUE self)
{
  VALUE level;

  if(rb_scan_args(argc, argv, "01", &level) == 0)
    level = INT2NUM(1);

  xmlDocPtr doc, dup;
  Data_Get_Struct(self, xmlDoc, doc);

  dup = xmlCopyDoc(doc, NUM2INT(level));
  if(dup == NULL) return Qnil;

  dup->type = doc->type;
  if(dup->type == XML_DOCUMENT_NODE)
    return Nokogiri_wrap_xml_document(cNokogiriXmlDocument, dup);
  else
    return Nokogiri_wrap_xml_document(cNokogiriHtmlDocument, dup);
}
Пример #14
0
/**
 * gda_report_engine_run_as_doc
 * @engine: a #GdaReportEngine object
 * @error: a place to store errors, or %NULL
 *
 * Execute the @engine engine and creates a new XML document
 *
 * Returns: a new xmlDocPtr or %NULL if an error occurred
 */
xmlDocPtr
gda_report_engine_run_as_doc (GdaReportEngine *engine, GError **error)
{
	xmlNodePtr retnode;
	xmlDocPtr doc;
	g_return_val_if_fail (GDA_IS_REPORT_ENGINE (engine), NULL);
	g_return_val_if_fail (engine->priv, NULL);
	g_return_val_if_fail (engine->priv->spec, NULL);

	retnode = gda_report_engine_run_as_node (engine, error);
	if (!retnode)
		return NULL;
	if (engine->priv->doc) 
		doc = xmlCopyDoc (engine->priv->doc, 1);
	else 
		doc = xmlNewDoc (BAD_CAST "1.0");
	xmlDocSetRootElement (doc, retnode);
	return doc;
}
Пример #15
0
static Variant HHVM_METHOD(XSLTProcessor, transformToDoc,
                           const Object& doc) {
  auto data = Native::data<XSLTProcessorData>(this_);

  if (doc.instanceof(s_DOMNode)) {
    auto domnode = Native::data<DOMNode>(doc);
    data->m_doc =
      libxml_register_node(xmlCopyDoc((xmlDocPtr)domnode->nodep(),
                                      /*recursive*/ 1));

    auto ret = newDOMDocument(false /* construct */);
    DOMNode* doc_data = Native::data<DOMNode>(ret);
    doc_data->setNode((xmlNodePtr)data->apply_stylesheet());

    return ret;
  }

  return false;
}
Пример #16
0
//---------------------------------------------------------------------------
int UnknownPolicy::import_schema_from_doc(xmlDocPtr doc, const std::string& filename)
{
    if (!doc)
    {
        error = "The document is not valid";
        return -1;
    }

    this->filename = filename;

    std::string name = filename;
    size_t pos = name.rfind("/");
    this->name = name.substr(pos == std::string::npos ? 0 : pos + 1);

    size_t ext_pos;
    if ((ext_pos = this->name.rfind(".")) != std::string::npos)
        this->name = this->name.substr(0, ext_pos);

    if (!this->name.length())
        this->name = "Policy example";

    if (!filename.size())
    {
        system_doc = xmlCopyDoc(doc, 1);
        return 0;
    }

    ZenLib::Ztring z_path = ZenLib::Ztring().From_UTF8(filename);
    if (ZenLib::File::Exists(z_path))
        return 0;

    int ret = xmlSaveFormatFile(this->filename.c_str(), doc, 2);

    if (ret < 0)
    {
        error = "Cannot copy the policy";
        return -1;
    }

    return 0;
}
Пример #17
0
static Variant HHVM_METHOD(XSLTProcessor, transformToURI,
                           const Object& doc,
                           const String& uri) {
  auto data = Native::data<XSLTProcessorData>(this_);

  if (!FileUtil::checkPathAndWarn(uri, "XSLTProcessor::transformToUri", 2)) {
    return false;
  }

  if (doc.instanceof(s_DOMDocument)) {
    auto domdoc = Native::data<DOMNode>(doc);
    data->m_doc =
      libxml_register_node(xmlCopyDoc ((xmlDocPtr)domdoc->nodep(),
                                       /*recursive*/ 1));

    String translated = libxml_get_valid_file_path(uri);
    if (translated.empty()) {
      raise_warning("Invalid URI");
      return false;
    }

    xmlDocPtr res = data->apply_stylesheet ();
    if (res == nullptr) {
      return false;
    }

    int bytes = xsltSaveResultToFilename(translated.data(),
                                         res,
                                         data->m_stylesheet,
                                         /*compression*/ 0);
    xmlFreeDoc(res);

    if (bytes == -1) {
      return false;
    }

    return bytes;
  }

  return false;
}
Пример #18
0
/*
 * Adds XML doc for a fault to the in-memory fault registry (doc).
 * Creates registry if none exists yet.
 *
 * Can also add COMMON_PREFIX (<common>) block.
 */
static boolean
add_eucafault (const xmlDoc *new_doc)
{
    if (xmlDocGetRootElement (ef_doc) == NULL) {
        logprintfl (EUCATRACE, "Creating new document.\n");
        ef_doc = xmlCopyDoc ((xmlDoc *)new_doc, 1); /* 1 == recursive copy */

        if (ef_doc == NULL) {
            logprintfl (EUCAERROR, "Problem creating fault registry.\n");
            return FALSE;
        }
    } else {
        logprintfl (EUCATRACE, "Appending to existing document.\n");
        if (xmlAddNextSibling (xmlFirstElementChild (xmlDocGetRootElement (ef_doc)),
                               xmlFirstElementChild (xmlDocGetRootElement ((xmlDoc *)new_doc))) == NULL) {
            logprintfl (EUCAERROR, "Problem adding fault to existing registry.\n");
            return FALSE;
        }
    }
    return TRUE;
}
Пример #19
0
xmlNodePtr
PmmCloneNode( xmlNodePtr node, int recursive )
{
    xmlNodePtr retval = NULL;

    if ( node != NULL ) {
        switch ( node->type ) {
        case XML_ELEMENT_NODE:
        case XML_TEXT_NODE:
        case XML_CDATA_SECTION_NODE:
        case XML_ENTITY_REF_NODE:
        case XML_PI_NODE:
        case XML_COMMENT_NODE:
        case XML_DOCUMENT_FRAG_NODE:
        case XML_ENTITY_DECL:
            retval = xmlCopyNode( node, recursive ? 1 : 2 );
            break;
        case XML_ATTRIBUTE_NODE:
            retval = (xmlNodePtr) xmlCopyProp( NULL, (xmlAttrPtr) node );
            break;
        case XML_DOCUMENT_NODE:
        case XML_HTML_DOCUMENT_NODE:
            retval = (xmlNodePtr) xmlCopyDoc( (xmlDocPtr)node, recursive );
            break;
        case XML_DOCUMENT_TYPE_NODE:
        case XML_DTD_NODE:
            retval = (xmlNodePtr) xmlCopyDtd( (xmlDtdPtr)node );
            break;
        case XML_NAMESPACE_DECL:
            retval = ( xmlNodePtr ) xmlCopyNamespace( (xmlNsPtr) node );
            break;
        default:
            break;
        }
    }

    return retval;
}
Пример #20
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);
}
Пример #21
0
/*
 * call-seq:
 *  dup
 *
 * Copy this Document.  An optional depth may be passed in, but it defaults
 * to a deep copy.  0 is a shallow copy, 1 is a deep copy.
 */
static VALUE duplicate_document(int argc, VALUE *argv, VALUE self)
{
  xmlDocPtr doc, dup;
  VALUE copy;
  VALUE level;
  VALUE error_list      = rb_ary_new();

  if(rb_scan_args(argc, argv, "01", &level) == 0)
    level = INT2NUM((long)1);

  Data_Get_Struct(self, xmlDoc, doc);

  xmlResetLastError();
  xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);
  dup = xmlCopyDoc(doc, (int)NUM2INT(level));
  xmlSetStructuredErrorFunc(NULL, NULL);

  if(dup == NULL) return Qnil;

  dup->type = doc->type;
  copy = Nokogiri_wrap_xml_document(rb_obj_class(self), dup);
  rb_iv_set(copy, "@errors", error_list);
  return copy ;
}
Пример #22
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);
}
Пример #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
int
ofcds_editconfig(void *UNUSED(data), const nc_rpc * UNUSED(rpc),
                 NC_DATASTORE target, const char *config,
                 NC_EDIT_DEFOP_TYPE defop,
                 NC_EDIT_ERROPT_TYPE UNUSED(errop), struct nc_err **error)
{
    int ret = EXIT_FAILURE, running = 0;
    char *aux;
    int cfgds_new = 0;
    xmlDocPtr cfgds = NULL, cfg = NULL, cfg_clone = NULL;
    xmlNodePtr rootcfg;

    if (defop == NC_EDIT_DEFOP_NOTSET) {
        defop = NC_EDIT_DEFOP_MERGE;
    }

    cfg = xmlReadMemory(config, strlen(config), NULL, NULL, XML_READ_OPT);
    rootcfg = xmlDocGetRootElement(cfg);
    if (!cfg
        || (rootcfg
            && !xmlStrEqual(rootcfg->name, BAD_CAST "capable-switch"))) {
        nc_verb_error("Invalid <edit-config> configuration data.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "config");
        return EXIT_FAILURE;
    }

    switch (target) {
    case NC_DATASTORE_RUNNING:
        /* Make a copy of parsed config - we will find port/configuration in
         * it.  It is used after txn_commit(). */
        cfg_clone = xmlCopyDoc(cfg, 1);

        aux = ofc_get_config_data();
        if (!aux) {
            *error = nc_err_new(NC_ERR_OP_FAILED);
            goto error_cleanup;
        }
        cfgds = xmlReadMemory(aux, strlen(aux), NULL, NULL, XML_READ_OPT);
        free(aux);

        running = 1;
        break;
    case NC_DATASTORE_STARTUP:
        cfgds = gds_startup;
        break;
    case NC_DATASTORE_CANDIDATE:
        cfgds = gds_cand;
        break;
    default:
        nc_verb_error("Invalid <edit-config> target.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "target");
        goto error_cleanup;
    }
    store_rollback(xmlCopyDoc(cfgds, 1), target);

    /* check keys in config's lists */
    ret = check_keys(cfg, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }

    /* check operations */
    ret = check_edit_ops(NC_EDIT_OP_DELETE, defop, cfgds, cfg, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }
    ret = check_edit_ops(NC_EDIT_OP_CREATE, defop, cfgds, cfg, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }

    if (target == NC_DATASTORE_RUNNING) {
        txn_init();
    }

    ret = compact_edit_operations(cfg, defop);
    if (ret != EXIT_SUCCESS) {
        nc_verb_error("Compacting edit-config operations failed.");
        if (error != NULL) {
            *error = nc_err_new(NC_ERR_OP_FAILED);
        }
        goto error_cleanup;
    }

    /* perform operations */
    if (!cfgds) {
        cfgds_new = 1;
        cfgds = xmlNewDoc(BAD_CAST "1.0");
    }
    ret = edit_operations(cfgds, cfg, defop, running, error);
    if (ret != EXIT_SUCCESS) {
        goto error_cleanup;
    }

    /* with defaults capability */
    if (ncdflt_get_basic_mode() == NCWD_MODE_TRIM) {
        /* server work in trim basic mode and therefore all default values
         * must be removed from the datastore. */
        /* TODO */
    }

    if (target == NC_DATASTORE_RUNNING) {
        ret = txn_commit(error);

        if (ret == EXIT_SUCCESS) {
            /* modify port/configuration of ports that were created */
            ret = of_post_ports(xmlDocGetRootElement(cfg_clone), error);
        }
        /* config clone was used and it is not needed by now */
        xmlFreeDoc(cfg_clone);

        xmlFreeDoc(cfgds);
    } else if (cfgds_new){
        if (cfgds->children) {
            /* document changed, because we started with empty document */
            if (target == NC_DATASTORE_STARTUP) {
                gds_startup = cfgds;
                cfgds = NULL;
            } else if (target == NC_DATASTORE_CANDIDATE) {
                gds_cand = cfgds;
                cfgds = NULL;
            }
        }
        xmlFreeDoc(cfgds);
    }
    xmlFreeDoc(cfg);

    return ret;

error_cleanup:

    if (target == NC_DATASTORE_RUNNING) {
        txn_abort();
        xmlFreeDoc(cfg_clone);
        xmlFreeDoc(cfgds);
    }
    xmlFreeDoc(cfg);

    return ret;
}
Пример #25
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;
}
Пример #26
0
OSyncConvCmpResult osync_xml_compare(xmlDoc *leftinpdoc, xmlDoc *rightinpdoc, OSyncXMLScore *scores, int default_score, int treshold)
{
	int z = 0, i = 0, n = 0;
	int res_score = 0;
	xmlDoc *leftdoc = NULL;
	xmlDoc *rightdoc = NULL;

	osync_trace(TRACE_ENTRY, "%s(%p, %p, %p)", __func__, leftinpdoc, rightinpdoc, scores);
	
	leftdoc = xmlCopyDoc(leftinpdoc, TRUE);
	rightdoc = xmlCopyDoc(rightinpdoc, TRUE);
	
	osync_trace(TRACE_INTERNAL, "Comparing given score list");
	while (scores && scores[z].path) {
		OSyncXMLScore *score = &scores[z];
		xmlXPathObject *leftxobj = osync_xml_get_nodeset(leftdoc, score->path);
		xmlXPathObject *rightxobj = osync_xml_get_nodeset(rightdoc, score->path);
		
		xmlNodeSet *lnodes = leftxobj->nodesetval;
		xmlNodeSet *rnodes = rightxobj->nodesetval;
		
		int lsize = (lnodes) ? lnodes->nodeNr : 0;
		int rsize = (rnodes) ? rnodes->nodeNr : 0;
		z++;
		osync_trace(TRACE_INTERNAL, "parsing next path %s", score->path);
		
		if (!score->value) {
			for (i = 0; i < lsize; i++) {
				xmlUnlinkNode(lnodes->nodeTab[i]);
				xmlFreeNode(lnodes->nodeTab[i]);
				lnodes->nodeTab[i] = NULL;
			}
			
			for (n = 0; n < rsize; n++) {
				xmlUnlinkNode(rnodes->nodeTab[n]);
				xmlFreeNode(rnodes->nodeTab[n]);
				rnodes->nodeTab[n] = NULL;
			}
		} else {
			for (i = 0; i < lsize; i++) {
				if (!lnodes->nodeTab[i])
					continue;
				for (n = 0; n < rsize; n++) {
					xmlChar *lcontent = NULL;
					xmlChar *rcontent = NULL;
					if (!rnodes->nodeTab[n])
						continue;
					lcontent = osync_xml_find_node(lnodes->nodeTab[i], "Content");
					rcontent = osync_xml_find_node(rnodes->nodeTab[n], "Content"); 
					osync_trace(TRACE_INTERNAL, "cmp %i:%s (%s), %i:%s (%s)", i, lnodes->nodeTab[i]->name, lcontent, n, rnodes->nodeTab[n]->name, rcontent);
					xmlFree(lcontent);
					xmlFree(rcontent);

					if (osync_xml_compare_node(lnodes->nodeTab[i], rnodes->nodeTab[n])) {
						osync_trace(TRACE_INTERNAL, "Adding %i for %s", score->value, score->path);
						res_score += score->value;
						xmlUnlinkNode(lnodes->nodeTab[i]);
						xmlFreeNode(lnodes->nodeTab[i]);
						lnodes->nodeTab[i] = NULL;
						xmlUnlinkNode(rnodes->nodeTab[n]);
						xmlFreeNode(rnodes->nodeTab[n]);
						rnodes->nodeTab[n] = NULL;
						goto next;
					}
				}
				osync_trace(TRACE_INTERNAL, "Subtracting %i for %s", score->value, score->path);
				res_score -= score->value;
			next:;
			}
			for(i = 0; i < rsize; i++) {
				if (!rnodes->nodeTab[i])
					continue;
				res_score -= score->value;
			}
		}
		
		xmlXPathFreeObject(leftxobj);
		xmlXPathFreeObject(rightxobj);
	}

	{ /* Block for new variables */
		xmlXPathObject *leftxobj = osync_xml_get_nodeset(leftdoc, "/*/*");
		xmlXPathObject *rightxobj = osync_xml_get_nodeset(rightdoc, "/*/*");
	
		xmlNodeSet *lnodes = leftxobj->nodesetval;
		xmlNodeSet *rnodes = rightxobj->nodesetval;
	
		int lsize = (lnodes) ? lnodes->nodeNr : 0;
		int rsize = (rnodes) ? rnodes->nodeNr : 0;
		osync_bool same = TRUE;
		osync_trace(TRACE_INTERNAL, "Comparing remaining list");

		for(i = 0; i < lsize; i++) {		
			for (n = 0; n < rsize; n++) {
				xmlChar *lcontent = NULL;
				xmlChar *rcontent = NULL;

				if (!rnodes->nodeTab[n])
					continue;

				lcontent = osync_xml_find_node(lnodes->nodeTab[i], "Content");
				rcontent = osync_xml_find_node(rnodes->nodeTab[n], "Content"); 

				osync_trace(TRACE_INTERNAL, "cmp %i:%s (%s), %i:%s (%s)", i, lnodes->nodeTab[i]->name, lcontent, n, rnodes->nodeTab[n]->name, rcontent);

				xmlFree(lcontent);
				xmlFree(rcontent);

				if (osync_xml_compare_node(lnodes->nodeTab[i], rnodes->nodeTab[n])) {
					xmlUnlinkNode(lnodes->nodeTab[i]);
					xmlFreeNode(lnodes->nodeTab[i]);
					lnodes->nodeTab[i] = NULL;
					xmlUnlinkNode(rnodes->nodeTab[n]);
					xmlFreeNode(rnodes->nodeTab[n]);
					rnodes->nodeTab[n] = NULL;
					osync_trace(TRACE_INTERNAL, "Adding %i", default_score);
					res_score += default_score;
					goto next2;
				}
			}
			osync_trace(TRACE_INTERNAL, "Subtracting %i", default_score);
			res_score -= default_score;
			same = FALSE;
			//goto out;
		next2:;
		}
	
		for(i = 0; i < lsize; i++) {
			if (!lnodes->nodeTab[i])
				continue;
			osync_trace(TRACE_INTERNAL, "left remaining: %s", lnodes->nodeTab[i]->name);
			same = FALSE;
			goto out;
		}
	
		for(i = 0; i < rsize; i++) {
			if (!rnodes->nodeTab[i])
				continue;
			osync_trace(TRACE_INTERNAL, "right remaining: %s", rnodes->nodeTab[i]->name);
			same = FALSE;
			goto out;
		}
	out:
		xmlXPathFreeObject(leftxobj);
		xmlXPathFreeObject(rightxobj);

		osync_xml_free_doc(leftdoc);
		osync_xml_free_doc(rightdoc);	
				

		osync_trace(TRACE_INTERNAL, "Result is: %i, Treshold is: %i", res_score, treshold);
		if (same) {
			osync_trace(TRACE_EXIT, "%s: SAME", __func__);
			return OSYNC_CONV_DATA_SAME;
		}
	} /* Block for new variables */
	if (res_score >= treshold) {
		osync_trace(TRACE_EXIT, "%s: SIMILAR", __func__);
		return OSYNC_CONV_DATA_SIMILAR;
	}
	osync_trace(TRACE_EXIT, "%s: MISMATCH", __func__);
	return OSYNC_CONV_DATA_MISMATCH;
}
Пример #27
0
static xmlDocPtr php_xsl_apply_stylesheet(zval *id, xsl_object *intern, xsltStylesheetPtr style, zval *docp) /* {{{ */
{
	xmlDocPtr newdocp = NULL;
	xmlDocPtr doc = NULL;
	xmlNodePtr node = NULL;
	xsltTransformContextPtr ctxt;
	php_libxml_node_object *object;
	char **params = NULL;
	int clone;
	zval *doXInclude, member, rv;
	zend_object_handlers *std_hnd;
	FILE *f;
	int secPrefsError = 0;
	int secPrefsValue;
	xsltSecurityPrefsPtr secPrefs = NULL;

	node = php_libxml_import_node(docp);

	if (node) {
		doc = node->doc;
	}
	if (doc == NULL) {
		php_error_docref(NULL, E_WARNING, "Invalid Document");
		return NULL;
	}

	if (style == NULL) {
		php_error_docref(NULL, E_WARNING, "No stylesheet associated to this object");
		return NULL;
	}

	if (intern->profiling) {
		if (php_check_open_basedir(intern->profiling)) {
			f = NULL;
		} else {
			f = VCWD_FOPEN(intern->profiling, "w");
		}
	} else {
		f = NULL;
	}

	if (intern->parameter) {
		params = php_xsl_xslt_make_params(intern->parameter, 0);
	}

	intern->doc = emalloc(sizeof(php_libxml_node_object));
	memset(intern->doc, 0, sizeof(php_libxml_node_object));

	if (intern->hasKeys == 1) {
		doc = xmlCopyDoc(doc, 1);
	} else {
		object = Z_LIBXML_NODE_P(docp);
		intern->doc->document = object->document;
	}

	php_libxml_increment_doc_ref(intern->doc, doc);

	ctxt = xsltNewTransformContext(style, doc);
	ctxt->_private = (void *) intern;

	std_hnd = zend_get_std_object_handlers();

	ZVAL_STRING(&member, "doXInclude");
	doXInclude = std_hnd->read_property(id, &member, BP_VAR_IS, NULL, &rv);
	if (Z_TYPE_P(doXInclude) != IS_NULL) {
		convert_to_long(doXInclude);
		ctxt->xinclude = Z_LVAL_P(doXInclude);
	}
	zval_ptr_dtor(&member);

	secPrefsValue = intern->securityPrefs;

	/* if securityPrefs is set to NONE, we don't have to do any checks, but otherwise... */
	if (secPrefsValue != XSL_SECPREF_NONE) {
		secPrefs = xsltNewSecurityPrefs();
		if (secPrefsValue & XSL_SECPREF_READ_FILE ) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_READ_FILE, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_WRITE_FILE ) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_WRITE_FILE, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_CREATE_DIRECTORY ) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_READ_NETWORK) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_READ_NETWORK, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}
		if (secPrefsValue & XSL_SECPREF_WRITE_NETWORK) {
			if (0 != xsltSetSecurityPrefs(secPrefs, XSLT_SECPREF_WRITE_NETWORK, xsltSecurityForbid)) {
				secPrefsError = 1;
			}
		}

		if (0 != xsltSetCtxtSecurityPrefs(secPrefs, ctxt)) {
			secPrefsError = 1;
		}
	}

	if (secPrefsError == 1) {
		php_error_docref(NULL, E_WARNING, "Can't set libxslt security properties, not doing transformation for security reasons");
	} else {
		newdocp = xsltApplyStylesheetUser(style, doc, (const char**) params,  NULL, f, ctxt);
	}
	if (f) {
		fclose(f);
	}

	xsltFreeTransformContext(ctxt);
	if (secPrefs) {
		xsltFreeSecurityPrefs(secPrefs);
	}

	if (intern->node_list != NULL) {
		zend_hash_destroy(intern->node_list);
		FREE_HASHTABLE(intern->node_list);
		intern->node_list = NULL;
	}

	php_libxml_decrement_doc_ref(intern->doc);
	efree(intern->doc);
	intern->doc = NULL;

	if (params) {
		clone = 0;
		while(params[clone]) {
			efree(params[clone++]);
		}
		efree(params);
	}

	return newdocp;

}
Пример #28
0
int
ofcds_copyconfig(void *UNUSED(data), NC_DATASTORE target,
                 NC_DATASTORE source, char *config, struct nc_err **error)
{
    int ret = EXIT_FAILURE;
    char *s;
    xmlDocPtr src_doc = NULL;
    xmlDocPtr dst_doc = NULL;
    xmlNodePtr root;
    static const char *ds[] = {"error", "<config>", "URL", "running",
                               "startup", "candidate"};

    nc_verb_verbose("OFC COPY-CONFIG (from %s to %s)", ds[source], ds[target]);

    switch (source) {
    case NC_DATASTORE_RUNNING:
        s = ofcds_getconfig(NULL, NC_DATASTORE_RUNNING, error);
        if (!s) {
            nc_verb_error
                ("copy-config: unable to get running source repository");
            return EXIT_FAILURE;
        }
        src_doc = xmlReadMemory(s, strlen(s), NULL, NULL, XML_READ_OPT);
        free(s);
        if (!src_doc) {
            nc_verb_error("copy-config: invalid running source data");
            *error = nc_err_new(NC_ERR_OP_FAILED);
            nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM,
                       "invalid running source data");
            return EXIT_FAILURE;
        }
        break;
    case NC_DATASTORE_STARTUP:
        src_doc = xmlCopyDoc(gds_startup, 1);
        break;
    case NC_DATASTORE_CANDIDATE:
        src_doc = xmlCopyDoc(gds_cand, 1);
        break;
    case NC_DATASTORE_CONFIG:
        if (config && strlen(config) > 0) {
            src_doc = xmlReadMemory(config, strlen(config), NULL, NULL,
                                    XML_READ_OPT);
        }
        if (!config || (strlen(config) > 0 && !src_doc)) {
            nc_verb_error("Invalid source configuration data.");
            *error = nc_err_new(NC_ERR_BAD_ELEM);
            nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "config");
            return EXIT_FAILURE;
        }

        break;
    default:
        nc_verb_error("Invalid <get-config> source.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "source");
        return EXIT_FAILURE;
    }

    switch (target) {
    case NC_DATASTORE_RUNNING:
        /* apply source to OVSDB */

        s = ofcds_getconfig(NULL, NC_DATASTORE_RUNNING, error);
        if (!s) {
            nc_verb_error("copy-config: unable to get running source data");
            goto cleanup;
        }
        dst_doc = xmlReadMemory(s, strlen(s), NULL, NULL, XML_READ_OPT);
        free(s);

        root = xmlDocGetRootElement(src_doc);
        if (!dst_doc) {
            /* create envelope */
            dst_doc = xmlNewDoc(BAD_CAST "1.0");
        }
        if (!rollbacking) {
            store_rollback(xmlCopyDoc(dst_doc, 1), target);
        }

        txn_init();
        if (edit_replace(dst_doc, root, 1, error)) {
            txn_abort();
        } else {
            ret = txn_commit(error);
        }
        xmlFreeDoc(dst_doc);
        goto cleanup;
        break;
    case NC_DATASTORE_STARTUP:
    case NC_DATASTORE_CANDIDATE:
        /* create copy */
        if (src_doc) {
            dst_doc = src_doc;
            src_doc = NULL;
        }

        /* store the copy */
        if (target == NC_DATASTORE_STARTUP) {
            if (!rollbacking) {
                store_rollback(gds_startup, target);
            } else {
                xmlFreeDoc(gds_startup);
            }
            gds_startup = dst_doc;
        } else {                /* NC_DATASTORE_CANDIDATE */
            if (!rollbacking) {
                store_rollback(gds_cand, target);
            } else {
                xmlFreeDoc(gds_cand);
            }
            gds_cand = dst_doc;
        }

        break;
    default:
        nc_verb_error("Invalid <get-config> source.");
        *error = nc_err_new(NC_ERR_BAD_ELEM);
        nc_err_set(*error, NC_ERR_PARAM_INFO_BADELEM, "source");
        goto cleanup;
    }

    ret = EXIT_SUCCESS;

cleanup:
    xmlFreeDoc(src_doc);

    return ret;
}
Пример #29
0
void getXmlDoc(int sockfd, int read_status, int read_config) {

    if(DEBUG>1) printf("[ getXmlDoc ]: from socket %d (read_status %d read_config %d)\n",sockfd,read_status,read_config);

    // check that I'm not already polling it
    if(xml_poll_status==1) {
        if(DEBUG>1) printf("[ getXmlDoc ]: already polling so don't continue for this process (%d,%p)\n",xml_poll_status,xml_string);    
        return;
    }

    // occupy the poll flag
    xml_poll_status = 1;

    //clear old documents
    if(DEBUG>2) printf("[ getXmlDoc ]: free xml string %p\n",xml_string);
    free_xml_string();
    //if(xml_string!=NULL) {
    //  free(xml_string);
    //}
    if(DEBUG>2) printf("[ getXmlDoc ]: free xml string done %p\n",xml_string);
    if(doc!=NULL) {
       
       if(doc_prev!=NULL) {
          if(DEBUG>2) printf("[ getXmlDoc ]: free the prev xml doc\n");
          xmlFreeDoc(doc_prev);
          doc_prev=NULL;
       }
       if(DEBUG>2) printf("[ getXmlDoc ]: copy to prev xml doc\n");
       doc_prev = xmlCopyDoc(doc,1);
       
       if(DEBUG>2) printf("[ getXmlDoc ]: free current xml doc\n");       
       xmlFreeDoc(doc);
       xmlCleanupParser();
       doc=NULL;
       xml_root=NULL;
    }
    if(DEBUG>2) printf("[ getXmlDoc ]: free xml doc done\n");

    // check that the socket is open
    if(sockfd<=0) {
        if(DEBUG>2) printf("[ getXmlDoc ]: socket is not open.\n");
        //clear the flag
        xml_poll_status = 0;
        return;
    }


    // Do a status and config read to be sure to catch all info
    // Need to see exactly how the falgs are set in the return string 
    // from the server to see what to do here.

    if(read_status>0) {

        if(DEBUG>2) printf("[ getXmlDoc ]: ReadStatus\n");

        writeReadStatus(sockfd);

    }

    if(read_config>0) {

        if(DEBUG>2) printf("[ getXmlDoc ]: ReadConfig\n");

        writeReadConfig(sockfd);

    }

    if(DEBUG>2) printf("[ getXmlDoc ]: Before reading xml string (%p)\n",xml_string);

    pollXmlString(sockfd);

    if(DEBUG>2) printf("[ getXmlDoc ]: After reading xml string (%p)\n",xml_string);

    if(xml_string!=NULL) {
        if(strlen(xml_string)>0) {
           if(DEBUG>1) printf("[ getXmlDoc ]: create xml document from xml string(strlen %d)\n",strlen(xml_string));
            if(DEBUG>1) printf("[ getXmlDoc ]: xml string:\n%s\n",xml_string);
            doc = xmlReadMemory(xml_string,strlen(xml_string),"noname.xml",NULL,0);
            if(DEBUG>1) printf("[ getXmlDoc ]: xml doc done %p\n",doc);
            if(doc!=NULL) {
                xml_root = xmlDocGetRootElement(doc);
                if(xml_root!=NULL) {
                   if(DEBUG>2) {
                      printf("[ getXmlDoc ]: found xml_root name %s\n",(xml_root)->name);
                      printf("[ getXmlDoc ]: print xml to file\n");
                   }
                   int bytes_written = xmlSaveFormatFile("svtdaq.xml",doc,1);
                   if(DEBUG>2) {
                      printf("[ getXmlDoc ]: printed %d bytes of xml to file\n",bytes_written);
                   }
                }
            } else {
                printf("[ getXmlDoc ]: [ ERROR ]: problem building xml doc at %p from \n%s\n",doc,xml_string);
                exit(1);
            }
        } else {
            printf("[ getXmlDoc ]: [ ERROR ]: xml_string is there but has zero string length!\n");	
            exit(1);
        }
    } else {
        printf("[ getXmlDoc ]: [ WARNING ]:  xml_string is NULL after reading from socket!\n");	
    }

    //clear the flag
    xml_poll_status = 0;
    if(DEBUG>0) printf("[ getXmlDoc ]: cleared the flag and return (%d)\n",xml_poll_status);

}
Пример #30
0
int copyDocument(const TixiDocumentHandle oldTixiDocumentHandle, TixiDocumentHandle* newTixiDocumentHandle)
{
  TixiDocument* srcDocument = getDocument(oldTixiDocumentHandle);
  TixiDocument* dstDocument = NULL;
  xmlDocPtr xmlDocument = NULL;
  xmlNodePtr rootNode = NULL;

  if (!srcDocument) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Invalid document handle.\n");
    return FAILED;
  }

  /* make a deep copy of the document */
  xmlDocument = xmlCopyDoc(srcDocument->docPtr, 1);

  if (!xmlDocument) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Could not copy document.\n");
    return FAILED;
  }

  rootNode = xmlDocGetRootElement(xmlDocument);
  if (!rootNode) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Could not get root node in source document.\n");
    return EROROR_CREATE_ROOT_NODE;
  }

  dstDocument = (TixiDocument*) malloc(sizeof(TixiDocument));

  /* copy attributes from source document */
  if (srcDocument->xmlFilename != NULL) {
    dstDocument->xmlFilename = (char*) malloc(sizeof(char) * strlen(srcDocument->xmlFilename) + 1);
    strcpy(dstDocument->xmlFilename, srcDocument->xmlFilename);
  }
  else {
    dstDocument->xmlFilename = NULL;
  }

  if (srcDocument->dirname != NULL) {
    dstDocument->dirname = (char*) malloc(sizeof(char) * strlen(srcDocument->dirname) + 1);
    strcpy(dstDocument->dirname, srcDocument->dirname);
  }
  else {
    dstDocument->dirname = NULL;
  }

  if (srcDocument->filename != NULL) {
    dstDocument->filename = (char*) malloc(sizeof(char) * strlen(srcDocument->filename) + 1);
    strcpy(dstDocument->filename, srcDocument->filename);
  }
  else {
    dstDocument->filename = NULL;
  }

  if (srcDocument->validationFilename != NULL) {
    dstDocument->validationFilename = (char*) malloc(sizeof(char) * strlen(srcDocument->validationFilename) + 1);
    strcpy(dstDocument->validationFilename, srcDocument->validationFilename);
  }
  else {
    dstDocument->validationFilename = NULL;
  }

  dstDocument->docPtr = xmlDocument;
  dstDocument->currentNode = rootNode;
  dstDocument->isValid = srcDocument->isValid;
  dstDocument->status = srcDocument->status;
  dstDocument->memoryListHead = NULL;
  dstDocument->memoryListTail = NULL;
  dstDocument->uidListHead = NULL;
  dstDocument->hasIncludedExternalFiles = srcDocument->hasIncludedExternalFiles;
  dstDocument->usePrettyPrint = srcDocument->usePrettyPrint;

  if (addDocumentToList(dstDocument, &(dstDocument->handle)) != SUCESS) {
    printMsg(MESSAGETYPE_ERROR, "Error in TIXI::copyDocument => Failed  adding document to document list.");
    return FAILED;
  }

  *newTixiDocumentHandle = dstDocument->handle;
  return SUCCESS;
}