XmlConfig::XmlConfigData::XmlConfigData(const char *file) : doc_(NULL), filename_(file) { namespace fs = boost::filesystem; std::string file_str; #ifdef BOOST_FILESYSTEM_VERSION #if BOOST_FILESYSTEM_VERSION == 3 fs::path path(file); file_str = path.native(); #else fs::path path(file, fs::no_check); file_str = path.native_file_string(); #endif #else fs::path path(file, fs::no_check); file_str = path.native_file_string(); #endif if (!fs::exists(path)) { std::stringstream stream; stream << "can not read " << file_str; throw std::runtime_error(stream.str()); } doc_ = XmlDocHelper(xmlParseFile(file_str.c_str())); XmlUtils::throwUnless(NULL != doc_.get()); if (NULL == xmlDocGetRootElement(doc_.get())) { throw std::logic_error("got empty config"); } XmlUtils::throwUnless(xmlXIncludeProcess(doc_.get()) >= 0); findVariables(doc_); }
int read_xml(const char *filename, const char *catalog) { xml_reader *reader = xmlReaders; xmlDocPtr doc; if (catalog) { xmlLoadCatalog(catalog); } #ifdef XML_PARSE_XINCLUDE doc = xmlReadFile(filename, NULL, XML_PARSE_XINCLUDE); #else doc = xmlParseFile(filename); #endif if (doc == NULL) { log_error("could not open %s\n", filename); return -1; } xmlXIncludeProcess(doc); while (reader != NULL) { int i = reader->callback(doc); if (i != 0) { return i; } reader = reader->next; } xmlFreeDoc(doc); return 0; }
/** * execute_xpath_expression: * @filename: the input XML filename. * @xpathExpr: the xpath expression for evaluation. * @nsList: the optional list of known namespaces in * "<prefix1>=<href1> <prefix2>=href2> ..." format. * * Parses input XML file, evaluates XPath expression and prints results. * * Returns 0 on success and a negative value otherwise. */ int execute_xpath_expression(const char* filename, const xmlChar* xpathExpr, const xmlChar* nsList) { xmlDocPtr doc; xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj; assert(filename); assert(xpathExpr); /* Load XML document */ doc = xmlParseFile(filename); if (doc == NULL) { fprintf(stderr, "Error: unable to parse file \"%s\"\n", filename); return(-1); } /* process XIncludes to enable the inclusion of dynamic or reference documentation */ if (0 > xmlXIncludeProcess(doc)) { fprintf(stderr, "Error: unable to process xincludes in file \"%s\"\n", filename); return(-1); } /* Create xpath evaluation context */ xpathCtx = xmlXPathNewContext(doc); if(xpathCtx == NULL) { fprintf(stderr,"Error: unable to create new XPath context\n"); xmlFreeDoc(doc); return(-1); } /* Register namespaces from list (if any) */ if((nsList != NULL) && (register_namespaces(xpathCtx, nsList) < 0)) { fprintf(stderr,"Error: failed to register namespaces list \"%s\"\n", nsList); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); return(-1); } /* Evaluate xpath expression */ xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx); if(xpathObj == NULL) { fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", xpathExpr); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); return(-1); } /* Print results */ //print_xpath_nodes(xpathObj->nodesetval, stdout); print_xpath_node_values(xpathObj->nodesetval, stdout); /* Cleanup */ xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); return(0); }
void xml_settings::init(char const *name) { doc_.reset(xmlParseFile(name)); xml::throw_unless(doc_); if (0 == xmlDocGetRootElement(doc_.get())) { throw error("empty config %s", name); } xml::throw_unless(xmlXIncludeProcess(doc_.get()) >= 0); find_variables(); }
//---------------------------------------------------------------------------- // SAXParsor::start //---------------------------------------------------------------------------- void SAXParsor::start(const std::string& document_path, INodeAnalyser* pRootAnalyser) { CDMA_STATIC_FUNCTION_TRACE("SAXParsor::start"); static bool sbLibXmlInit = false; yat::log_info("cfg", "Loading XML file %s", PSZ(document_path)); if( false == sbLibXmlInit ) { // this initialize the library and check potential API mismatches // between the version it was compiled for and the actual shared // library used. // Since we can't initialize the library more than once // use a static bool to ensure this LIBXML_TEST_VERSION sbLibXmlInit = true; // Initialize threads stuff xmlInitThreads(); // To ensure that library will work in a multithreaded program xmlInitParser(); } // Read xml file and build document in memory xmlDoc *pDoc = xmlReadFile(PSZ(document_path), NULL, 0); if( NULL == pDoc ) { THROW_LIBXML2_EXCEPTION("Error while loading document", "SAXParsor::Start"); } // Apply xinclude subsitution int iRc = xmlXIncludeProcess(pDoc); if( iRc >= 0 ) { xmlErrorPtr ptrError = xmlGetLastError(); if( ptrError && ptrError->level > 1 ) { THROW_LIBXML2_EXCEPTION(yat::String::str_format("Error while parsing xml document: %s", ptrError->message), "SAXParsor::Start"); } // Retreive root element xmlNode *pRootNode = xmlDocGetRootElement(pDoc); // Start parsing giving a ConfigAnalyser as nodes interpretor yat::log_info("cfg", "Parsing configuration"); instance().parse_node(pRootNode, pRootAnalyser); } // Free the document xmlFreeDoc(pDoc); if( iRc < 0 ) // Error occured when applying xinclude subsitution THROW_LIBXML2_EXCEPTION("Error while applying xinclude subsitution", "SAXParsor::Start"); }
/** * create new NftPrefsNode from preferences file * * @param p NftPrefs context * @param filename full path of file * @result newly created NftPrefsNode or NULL */ NftPrefsNode *nft_prefs_node_from_file(NftPrefs *p, const char *filename) { if(!filename) NFT_LOG_NULL(NULL); /* parse XML */ xmlDocPtr doc; if(!(doc = xmlReadFile(filename, NULL, 0))) { NFT_LOG(L_ERROR, "Failed to xmlReadFile(\"%s\")", filename); return NULL; } /* parse XInclude stuff */ int xinc_res; if((xinc_res = xmlXIncludeProcess(doc)) == -1) { NFT_LOG(L_ERROR, "XInclude parsing failed."); goto _npnff_error; } NFT_LOG(L_DEBUG, "%d XInclude substitutions done", xinc_res); /* get node */ xmlNode *node; if(!(node = xmlDocGetRootElement(doc))) { NFT_LOG(L_ERROR, "No root element found in XML"); goto _npnff_error; } /* update node */ if(!_updater_node_process(p, node)) { NFT_LOG(L_ERROR, "Preference update failed for node \"%s\". This is a fatal bug. Aborting.", nft_prefs_node_get_name(node)); goto _npnff_error; } /* return node */ return node; _npnff_error: xmlFreeDoc(doc); return NULL; }
/** * xsltLoadDocument: * @ctxt: an XSLT transformation context * @URI: the computed URI of the document * * Try to load a document within the XSLT transformation context * * Returns the new xsltDocumentPtr or NULL in case of error */ xsltDocumentPtr xsltLoadDocument(xsltTransformContextPtr ctxt, const xmlChar *URI) { xsltDocumentPtr ret; xmlDocPtr doc; if ((ctxt == NULL) || (URI == NULL)) return(NULL); /* * Walk the context list to find the document if preparsed */ ret = ctxt->docList; while (ret != NULL) { if ((ret->doc != NULL) && (ret->doc->URL != NULL) && (xmlStrEqual(ret->doc->URL, URI))) return(ret); ret = ret->next; } doc = xmlParseFile((const char *) URI); if (doc == NULL) return(NULL); if (ctxt->xinclude != 0) { #ifdef LIBXML_XINCLUDE_ENABLED xmlXIncludeProcess(doc); #else xsltPrintErrorContext(ctxt, NULL, NULL); xsltGenericError(xsltGenericErrorContext, "xsltLoadDocument(%s) : XInclude processing not compiled in\n", URI); #endif } /* * Apply white-space stripping if asked for */ if (xsltNeedElemSpaceHandling(ctxt)) xsltApplyStripSpaces(ctxt, xmlDocGetRootElement(doc)); ret = xsltNewDocument(ctxt, doc); return(ret); }
static void xml_config_open(void) { if (!getcwd(gfs_root_dir, FILENAME_MAX)) { yaz_log(YLOG_WARN|YLOG_ERRNO, "getcwd failed"); gfs_root_dir[0] = '\0'; } #ifdef WIN32 init_control_tls = 1; current_control_tls = TlsAlloc(); #elif YAZ_POSIX_THREADS init_control_tls = 1; pthread_key_create(¤t_control_tls, 0); #endif gfs_nmem = nmem_create(); #if YAZ_HAVE_XML2 if (control_block.xml_config[0] == '\0') return; if (!xml_config_doc) { xml_config_doc = xmlParseFile(control_block.xml_config); if (!xml_config_doc) { yaz_log(YLOG_FATAL, "Could not parse %s", control_block.xml_config); exit(1); } else { int noSubstitutions = xmlXIncludeProcess(xml_config_doc); if (noSubstitutions == -1) { yaz_log(YLOG_WARN, "XInclude processing failed for config %s", control_block.xml_config); exit(1); } } } xml_config_read(); #endif }
XmlConfig::XmlConfig(const char *file) : doc_(nullptr), regex_("\\$\\{([A-Za-z][A-Za-z0-9\\-]*)\\}") { try { std::ifstream f(file); if (!f) { throw std::runtime_error(std::string("can not open ").append(file)); } setFilename(file); doc_ = XmlDocHelper(xmlParseFile(file)); XmlUtils::throwUnless(nullptr != doc_.get()); if (nullptr == xmlDocGetRootElement(doc_.get())) { throw std::logic_error("got empty config"); } XmlUtils::throwUnless(xmlXIncludeProcess(doc_.get()) >= 0); findVariables(doc_); } catch (const std::ios::failure &e) { throw std::runtime_error(std::string("can not read ").append(file)); } }
xmlDocPtr parseDoc(std::string document, std::string baseUri, bool resolveXIncludes) { xmlDocPtr doc = xmlReadMemory(document.c_str(), document.size(), baseUri.c_str(), NULL, 0); if (doc == nullptr) { THROW_EXC("failed to parse xml queries"); } if (resolveXIncludes) { int ret = xmlXIncludeProcess(doc); if (ret < 0) { THROW_EXC("xinclude failed"); } } string schemaUrl; xmlNodePtr tmp = doc->children; while (tmp) { if (tmp->type == XML_ELEMENT_NODE) { xmlAttributePtr attr = ((xmlElementPtr)tmp)->attributes; while (attr) { if (string((char*)attr->name) == "noNamespaceSchemaLocation" && string("http://www.w3.org/2001/XMLSchema-instance") == (char*)((xmlNodePtr)attr)->ns->href ) { schemaUrl = (char*)attr->children->content; } attr = (xmlAttribute*)attr->next; } } tmp = tmp->next; } LOG_INFO("using schema '" << schemaUrl << "' for validating"); char *absUri = (char*)xmlBuildURI((xmlChar*)schemaUrl.c_str(),(xmlChar*)baseUri.c_str()); if (!schemaUrl.empty()) { validateDoc(doc,baseUri, string(absUri)); } return doc; }
/* * call-seq: * document.xinclude -> num * * Process xinclude directives in this document. */ static VALUE rxml_document_xinclude(VALUE self) { #ifdef LIBXML_XINCLUDE_ENABLED xmlDocPtr xdoc; int ret; Data_Get_Struct(self, xmlDoc, xdoc); ret = xmlXIncludeProcess(xdoc); if (ret >= 0) { return(INT2NUM(ret)); } else { rxml_raise(&xmlLastError); return Qnil; } #else rb_warn( "libxml was compiled without XInclude support. Please recompile libxml and ruby-libxml"); return (Qfalse); #endif }
static void get_tone_set(const char *tone_file, const char *set_id) { xmlDocPtr doc; xmlNsPtr ns; xmlNodePtr cur; #if 0 xmlValidCtxt valid; #endif xmlChar *x; ns = NULL; xmlKeepBlanksDefault(0); xmlCleanupParser(); doc = xmlParseFile(tone_file); if (doc == NULL) { fprintf(stderr, "No document\n"); exit(2); } /*endif*/ xmlXIncludeProcess(doc); #if 0 if (!xmlValidateDocument(&valid, doc)) { fprintf(stderr, "Invalid document\n"); exit(2); } /*endif*/ #endif /* Check the document is of the right kind */ if ((cur = xmlDocGetRootElement(doc)) == NULL) { fprintf(stderr, "Empty document\n"); xmlFreeDoc(doc); exit(2); } /*endif*/ if (xmlStrcmp(cur->name, (const xmlChar *) "global-tones")) { fprintf(stderr, "Document of the wrong type, root node != global-tones"); xmlFreeDoc(doc); exit(2); } /*endif*/ cur = cur->xmlChildrenNode; while (cur && xmlIsBlankNode(cur)) cur = cur->next; /*endwhile*/ if (cur == NULL) exit(2); /*endif*/ while (cur) { if (xmlStrcmp(cur->name, (const xmlChar *) "tone-set") == 0) { if ((x = xmlGetProp(cur, (const xmlChar *) "uncode"))) { if (strcmp((char *) x, set_id) == 0) parse_tone_set(doc, ns, cur); /*endif*/ xmlFree(x); } /*endif*/ } /*endif*/ cur = cur->next; } /*endwhile*/ xmlFreeDoc(doc); }
static void xsltProcess(xmlDocPtr doc, xsltStylesheetPtr cur, const char *filename) { xmlDocPtr res; #ifdef LIBXML_XINCLUDE_ENABLED if (xinclude) { if (timing) gettimeofday(&begin, NULL); xmlXIncludeProcess(doc); 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, "XInclude processing %s took %ld ms\n", filename, msec); } } #endif if (timing) gettimeofday(&begin, NULL); if (output == NULL) { if (repeat) { int j; for (j = 1; j < repeat; j++) { res = xsltApplyStylesheet(cur, doc, params); xmlFreeDoc(res); xmlFreeDoc(doc); #ifdef LIBXML_HTML_ENABLED if (html) doc = htmlParseFile(filename, NULL); else #endif #ifdef LIBXML_DOCB_ENABLED if (docbook) doc = docbParseFile(filename, NULL); else #endif doc = xmlParseFile(filename); } } if (profile) { res = xsltProfileStylesheet(cur, doc, params, stderr); } else { res = xsltApplyStylesheet(cur, doc, params); } if (timing) { long msec; gettimeofday(&end, NULL); msec = end.tv_sec - begin.tv_sec; msec *= 1000; msec += (end.tv_usec - begin.tv_usec) / 1000; if (repeat) fprintf(stderr, "Applying stylesheet %d times took %ld ms\n", repeat, msec); else fprintf(stderr, "Applying stylesheet took %ld ms\n", msec); } xmlFreeDoc(doc); if (res == NULL) { fprintf(stderr, "no result for %s\n", filename); return; } if (noout) { xmlFreeDoc(res); return; } #ifdef LIBXML_DEBUG_ENABLED if (debug) xmlDebugDumpDocument(stdout, res); else { #endif if (cur->methodURI == NULL) { if (timing) gettimeofday(&begin, NULL); xsltSaveResultToFile(stdout, res, cur); 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, "Saving result took %ld ms\n", msec); } } else { if (xmlStrEqual (cur->method, (const xmlChar *) "xhtml")) { fprintf(stderr, "non standard output xhtml\n"); if (timing) gettimeofday(&begin, NULL); xsltSaveResultToFile(stdout, res, cur); 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, "Saving result took %ld ms\n", msec); } } else { fprintf(stderr, "Unsupported non standard output %s\n", cur->method); } } #ifdef LIBXML_DEBUG_ENABLED } #endif xmlFreeDoc(res); } else { xsltRunStylesheet(cur, doc, params, output, NULL, NULL); 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, "Running stylesheet and saving result took %ld ms\n", msec); } xmlFreeDoc(doc); } }
gboolean loadConfig(const gchar *filename, CfgFile *lcfg) { /* Parse hosts.xml document. */ xmlDocPtr xcfg = xmlParseFile(filename); if(xcfg == NULL) return(FALSE); /* Handle Xincludes. */ xmlSetGenericErrorFunc(NULL, xmlErrIgnoreHandler); xmlXIncludeProcess(xcfg); handleXMLError( xmlGetLastError() ); xmlSetGenericErrorFunc(NULL, NULL); /* Validate against DTD. */ xmlValidCtxtPtr xval = xmlNewValidCtxt(); if(xmlValidateDocument(xval, xcfg) == 0) { xmlFreeValidCtxt(xval); return(FALSE); } xmlFreeValidCtxt(xval); /* Allocate XPath context. */ xmlXPathContextPtr xctx = xmlXPathNewContext(xcfg); if(!xctx) { g_error("%s: xmlXPathNewContext failed!\n", filename); return(FALSE); } xmlNodePtr s_ssh[2] = {getXNode(xctx, "/apt-dater/ssh"), NULL}; xmlNodePtr s_path[2] = {getXNode(xctx, "/apt-dater/paths"), NULL}; #ifdef FEAT_TMUX xmlNodePtr s_tmux[2] = {getXNode(xctx, "/apt-dater/tmux"), NULL}; #else xmlNodePtr s_screen[2] = {getXNode(xctx, "/apt-dater/screen"), NULL}; #endif xmlNodePtr s_appearance[2] = {getXNode(xctx, "/apt-dater/appearance"), NULL}; xmlNodePtr s_notify[2] = {getXNode(xctx, "/apt-dater/notify"), NULL}; xmlNodePtr s_hooks[2] = {getXNode(xctx, "/apt-dater/hooks"), NULL}; #ifdef FEAT_AUTOREF xmlNodePtr s_autoref[2] = {getXNode(xctx, "/apt-dater/auto-ref"), NULL}; #endif #ifdef FEAT_HISTORY xmlNodePtr s_history[2] = {getXNode(xctx, "/apt-dater/history"), NULL}; #endif #ifdef FEAT_TCLFILTER xmlNodePtr s_tclfilter[2] = {getXNode(xctx, "/apt-dater/tcl-filter"), NULL}; #endif lcfg->ssh_optflags = getXPropStr(s_ssh, "opt-cmd-flags", "-t"); lcfg->ssh_cmd = getXPropStr(s_ssh, "cmd", "/usr/bin/ssh"); lcfg->sftp_cmd = getXPropStr(s_ssh, "sftp-cmd", "/usr/bin/sftp"); lcfg->umask = getXPropInt(s_path, "umask", S_IRWXG | S_IRWXO); umask(lcfg->umask); lcfg->hostsfile = getXPropStr(s_path, "hosts-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "hosts.xml")); lcfg->statsdir = getXPropStr(s_path, "stats-dir", g_strdup_printf("%s/%s/%s", g_get_user_cache_dir(), PROG_NAME, "stats")); if(g_mkdir_with_parents(lcfg->statsdir, S_IRWXU | S_IRWXG) == -1) { g_warning("Failed to create %s: %s", lcfg->statsdir, g_strerror(errno)); exit(1); } #ifdef FEAT_TMUX lcfg->tmuxconffile = getXPropStr(s_tmux, "conf-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "tmux.conf")); lcfg->tmuxsockpath = getXPropStr(s_tmux, "socket-path", g_strdup_printf("%s/%s/%s", g_get_user_cache_dir(), PROG_NAME, "tmux")); if(g_mkdir_with_parents(lcfg->tmuxsockpath, S_IRWXU | S_IRWXG) == -1) { g_warning("Failed to create %s: %s", lcfg->tmuxsockpath, g_strerror(errno)); exit(1); } #else lcfg->screenrcfile = getXPropStr(s_screen, "rc-file", g_strdup_printf("%s/%s/%s", g_get_user_config_dir(), PROG_NAME, "screenrc")); lcfg->screentitle = getXPropStr(s_screen, "title", g_strdup("%m # %U%H")); #endif lcfg->ssh_agent = getXPropBool(s_ssh, "spawn-agent", FALSE); xmlNodeSetPtr s_addkeys = getXNodes(xctx, "/apt-dater/ssh/add-key"); if(!xmlXPathNodeSetIsEmpty(s_addkeys)) { lcfg->ssh_add = g_new0(char*, s_addkeys->nodeNr + 1); int i; for(i = 0; i < s_addkeys->nodeNr; i++) { lcfg->ssh_add[i] = g_strdup((gchar *)xmlGetProp(s_addkeys->nodeTab[i], BAD_CAST("name"))); xmlChar *c = xmlGetProp(s_addkeys->nodeTab[i], BAD_CAST("fn")); if(!c) { g_printerr(_("Empty SSH key filename (%s/@fn) in configuration."), xmlGetNodePath(s_addkeys->nodeTab[i])); exit(1); } lcfg->ssh_add[i] = g_strdup((gchar *)c); } lcfg->ssh_numadd = s_addkeys->nodeNr; }
/*! * \brief Finalize building of QXmlStreamReaderExt * * Factorize code. This code validate document and * transfer control to qt * \param docvoid[in]: xmlDocPtr doc of xml open * document * \param schema[in]: schema used could be null * \param xslt[in]: xslt transform to be used could be null * \note We use void cast in order to avoid exporting libxml * in .h */ void QXmlStreamReaderExt::finalize(const void * docvoid, const QRelaxNGvalidator * schema, const QXsltTransformer *xslt, bool usexinclude) { xmlDocPtr doc = (xmlDocPtr) docvoid; xmlDocPtr xslteddoc = NULL; int size; /* apply xinclude */ if(usexinclude) { if(xmlXIncludeProcess(doc) < 0) { goto errorxinclude; } } /* control schema */ if(schema) { if(schema->hasError()) { this->raiseError(schema->ErrorString()); goto notvalid; } /* validate */ if(schema->validate(doc) == false) { goto notvalid; } } /* apply xslt */ if(xslt != NULL) { if(xslt->hasError()) { this->raiseError(xslt->ErrorString()); goto outxslterror; } xslteddoc = (xmlDocPtr) xslt->transform(doc); if(xslteddoc == NULL) { goto outxslterror; } } else { /* null transform */ xslteddoc = doc; } /* save document */ xmlDocDumpMemory(xslteddoc, (xmlChar **)&xmlout, &size); /* free */ if(xslt != NULL) { xmlFreeDoc(xslteddoc); } xmlFreeDoc(doc); if(size < 0) { goto writeerror; } /* pass document to qt avoid copying data */ this->data = QByteArray::fromRawData((char *) xmlout, size); this->addData(this->data); return; errorxinclude: xmlFreeDoc(doc); qDebug() << "Xinclude error"; raiseError ("Xinclude error"); notvalid: xmlFreeDoc(doc); qDebug() << "Could not validate"; raiseError ("Could not validate"); return; outxslterror: qDebug() << "xslt error"; raiseError ("xslt error"); writeerror: qDebug() << "Could not save to memory"; raiseError ("Could not save to memory"); return; }
void process(document<S> &d) { xmlXIncludeProcess(impl(d));}
int cXmlDoc::xInclude() { if (!m_doc) throw eXmlInvalid("Tried to resolve xincludes for bad document"); return xmlXIncludeProcess(m_doc.get()); }