static CPLXMLSchemaPtr CPLLoadXMLSchema(const char* pszXSDFilename) { char* pszStr = CPLLoadSchemaStr(pszXSDFilename); if (pszStr == NULL) return NULL; xmlExternalEntityLoader pfnLibXMLOldExtranerEntityLoaderLocal = NULL; pfnLibXMLOldExtranerEntityLoaderLocal = xmlGetExternalEntityLoader(); pfnLibXMLOldExtranerEntityLoader = pfnLibXMLOldExtranerEntityLoaderLocal; xmlSetExternalEntityLoader(CPLExternalEntityLoader); xmlSchemaParserCtxtPtr pSchemaParserCtxt = xmlSchemaNewMemParserCtxt(pszStr, static_cast<int>(strlen(pszStr))); xmlSchemaSetParserErrors(pSchemaParserCtxt, CPLLibXMLWarningErrorCallback, CPLLibXMLWarningErrorCallback, NULL); xmlSchemaPtr pSchema = xmlSchemaParse(pSchemaParserCtxt); xmlSchemaFreeParserCtxt(pSchemaParserCtxt); xmlSetExternalEntityLoader(pfnLibXMLOldExtranerEntityLoaderLocal); CPLFree(pszStr); return (CPLXMLSchemaPtr) pSchema; }
static bool CPLHasLibXMLBug() { if (bHasLibXMLBug >= 0) return CPL_TO_BOOL(bHasLibXMLBug); static const char szLibXMLBugTester[] = "<schema targetNamespace=\"http://foo\" xmlns:foo=\"http://foo\" xmlns=\"http://www.w3.org/2001/XMLSchema\">" "<simpleType name=\"t1\">" "<list itemType=\"double\"/>" "</simpleType>" "<complexType name=\"t2\">" "<simpleContent>" "<extension base=\"foo:t1\"/>" "</simpleContent>" "</complexType>" "<complexType name=\"t3\">" "<simpleContent>" "<restriction base=\"foo:t2\">" "<length value=\"2\"/>" "</restriction>" "</simpleContent>" "</complexType>" "</schema>"; xmlSchemaParserCtxtPtr pSchemaParserCtxt; xmlSchemaPtr pSchema; pSchemaParserCtxt = xmlSchemaNewMemParserCtxt(szLibXMLBugTester, strlen(szLibXMLBugTester)); xmlSchemaSetParserErrors(pSchemaParserCtxt, CPLHasLibXMLBugWarningCallback, CPLHasLibXMLBugWarningCallback, NULL); pSchema = xmlSchemaParse(pSchemaParserCtxt); xmlSchemaFreeParserCtxt(pSchemaParserCtxt); bHasLibXMLBug = (pSchema == NULL); if (pSchema) xmlSchemaFree(pSchema); if (bHasLibXMLBug) { CPLDebug("CPL", "LibXML bug found (cf https://bugzilla.gnome.org/show_bug.cgi?id=630130). " "Will try to workaround for GML schemas."); } return CPL_TO_BOOL(bHasLibXMLBug); }
void schema::load_from_string(const char* str) { free_(); int size = static_cast<int>(std::strlen(str)); xmlSchemaParserCtxt* ctxt = xmlSchemaNewMemParserCtxt(str, size); if (ctxt != 0) { raw_ = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); } if (raw_ == 0) { throw dom_error("failed to load schema from string"); } }
void XMLParser::setSchema(const string& sSchema, const string& sSchemaName) { AVG_ASSERT(!m_SchemaParserCtxt); AVG_ASSERT(!m_Schema); AVG_ASSERT(!m_SchemaValidCtxt); AVG_ASSERT(!m_DTD); AVG_ASSERT(!m_DTDValidCtxt); m_SchemaParserCtxt = xmlSchemaNewMemParserCtxt(sSchema.c_str(), sSchema.length()); checkError(!m_SchemaParserCtxt, sSchemaName); m_Schema = xmlSchemaParse(m_SchemaParserCtxt); checkError(!m_Schema, sSchemaName); m_SchemaValidCtxt = xmlSchemaNewValidCtxt(m_Schema); checkError(!m_SchemaValidCtxt, sSchemaName); }
/*-----------------------------------------------------------------------------------------------------------------------*/ static FIXErrCode xml_validate(xmlDoc* doc, FIXError** error) { xmlSchemaParserCtxtPtr pctx = xmlSchemaNewMemParserCtxt(fix_xsd, strlen(fix_xsd)); xmlSchemaPtr schema = xmlSchemaParse(pctx); if (!schema) { return FIX_FAILED; } xmlSchemaValidCtxtPtr validCtx = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(validCtx, &xmlErrorHandler, &xmlErrorHandler, error); int32_t res = xmlSchemaValidateDoc(validCtx, doc); xmlSchemaFreeValidCtxt(validCtx); xmlSchemaFree(schema); xmlSchemaFreeParserCtxt(pctx); return res ? FIX_FAILED : FIX_SUCCESS; }
void CLibXmlValidator::validate() { if (!xmlFile.length() && !xml.length()) throw MakeStringException(XMLERR_MissingSource, "Source XML not provided"); if (!xsdFile.length() && !xsd.length()) throw MakeStringException(XMLERR_MissingSource, "XML Schema not provided"); xmlParserInputBufferPtr input; if (xmlFile.length()) input = xmlParserInputBufferCreateFilename(xmlFile.get(), XML_CHAR_ENCODING_NONE); else input = xmlParserInputBufferCreateMem(xml.str(), xml.length()+1, XML_CHAR_ENCODING_NONE); if (!input) throw MakeStringException(XMLERR_InvalidXml, "Failed to create XML input stream"); xmlSchemaParserCtxtPtr xsdParser; if (xsdFile.length()) xsdParser = xmlSchemaNewParserCtxt(xsdFile.get()); else xsdParser = xmlSchemaNewMemParserCtxt(xsd.str(), xsd.length()); if (!xsdParser) throw MakeStringException(XMLERR_InvalidXsd, "Failed to load XML Schema"); xmlSchemaSetParserErrors(xsdParser, libxmlXsdErrorMsgHandler, libxmlXsdErrorMsgHandler, this); xmlSchemaPtr schema = xmlSchemaParse(xsdParser); xmlSchemaFreeParserCtxt(xsdParser); if (!schema) throw MakeStringException(XMLERR_InvalidXsd, "XSD schema parsing failed"); xmlSchemaValidCtxtPtr validator = xmlSchemaNewValidCtxt(schema); xmlSchemaSetValidErrors(validator, libxmlXsdErrorMsgHandler, libxmlXsdErrorMsgHandler, this); int ret = xmlSchemaValidateStream(validator, input, XML_CHAR_ENCODING_NONE, emptySAXHandler, (void *)this); if (ret != 0) { ensureExceptions()->append(*MakeStringException(XMLERR_XsdValidationFailed, "XML validation failed")); throw exceptions.getClear(); } xmlSchemaFreeValidCtxt(validator); }
/* * call-seq: * read_memory(string) * * Create a new Schema from the contents of +string+ */ static VALUE read_memory(VALUE klass, VALUE content) { xmlSchemaParserCtxtPtr ctx = xmlSchemaNewMemParserCtxt( (const char *)StringValuePtr(content), (int)RSTRING_LEN(content) ); VALUE errors = rb_ary_new(); xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); #ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS xmlSchemaSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); #endif xmlSchemaPtr schema = xmlSchemaParse(ctx); xmlSetStructuredErrorFunc(NULL, NULL); xmlSchemaFreeParserCtxt(ctx); if(NULL == schema) { xmlErrorPtr error = xmlGetLastError(); if(error) Nokogiri_error_raise(NULL, error); else rb_raise(rb_eRuntimeError, "Could not parse document"); return Qnil; } VALUE rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema); rb_iv_set(rb_schema, "@errors", errors); return rb_schema; }
/* * call-seq: * read_memory(string) * * Create a new Schema from the contents of +string+ */ static VALUE read_memory(VALUE klass, VALUE content) { xmlSchemaParserCtxtPtr ctx = xmlSchemaNewMemParserCtxt( (const char *)StringValuePtr(content), RSTRING_LEN(content) ); VALUE errors = rb_ary_new(); xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); xmlSchemaSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); xmlSchemaPtr schema = xmlSchemaParse(ctx); xmlSetStructuredErrorFunc(NULL, NULL); xmlSchemaFreeParserCtxt(ctx); if(NULL == schema) { xmlErrorPtr error = xmlGetLastError(); if(error) rb_funcall(rb_mKernel, rb_intern("raise"), 1, Nokogiri_wrap_xml_syntax_error((VALUE)NULL, error) ); else rb_raise(rb_eRuntimeError, "Could not parse document"); return Qnil; } VALUE rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema); rb_iv_set(rb_schema, "@errors", errors); return rb_schema; }
HRESULT dt_validate(XDR_DT dt, xmlChar const* content) { xmlDocPtr tmp_doc; xmlNodePtr node; xmlNsPtr ns; HRESULT hr; TRACE("(dt:%s, %s)\n", debugstr_dt(dt), debugstr_a((char const*)content)); if (!datatypes_schema) { xmlSchemaParserCtxtPtr spctx; assert(datatypes_src != NULL); spctx = xmlSchemaNewMemParserCtxt((char const*)datatypes_src, datatypes_len); datatypes_schema = Schema_parse(spctx); xmlSchemaFreeParserCtxt(spctx); } switch (dt) { case DT_INVALID: return E_FAIL; case DT_BIN_BASE64: case DT_BIN_HEX: case DT_BOOLEAN: case DT_CHAR: case DT_DATE: case DT_DATE_TZ: case DT_DATETIME: case DT_DATETIME_TZ: case DT_FIXED_14_4: case DT_FLOAT: case DT_I1: case DT_I2: case DT_I4: case DT_I8: case DT_INT: case DT_NMTOKEN: case DT_NMTOKENS: case DT_NUMBER: case DT_R4: case DT_R8: case DT_STRING: case DT_TIME: case DT_TIME_TZ: case DT_UI1: case DT_UI2: case DT_UI4: case DT_UI8: case DT_URI: case DT_UUID: if (!datatypes_schema) { ERR("failed to load schema for urn:schemas-microsoft-com:datatypes, " "you're probably using an old version of libxml2: " LIBXML_DOTTED_VERSION "\n"); /* Hopefully they don't need much in the way of XDR datatypes support... */ return S_OK; } if (content && xmlStrlen(content)) { tmp_doc = xmlNewDoc(NULL); node = xmlNewChild((xmlNodePtr)tmp_doc, NULL, dt_to_str(dt), content); ns = xmlNewNs(node, DT_nsURI, BAD_CAST "dt"); xmlSetNs(node, ns); xmlDocSetRootElement(tmp_doc, node); hr = Schema_validate_tree(datatypes_schema, (xmlNodePtr)tmp_doc); xmlFreeDoc(tmp_doc); } else { /* probably the node is being created manually and has no content yet */ hr = S_OK; } return hr; default: FIXME("need to handle dt:%s\n", debugstr_dt(dt)); return S_OK; } }
/** * Validation function take first argument as XML type, then check if is * well formated. If so, do the same for XSD document. If both success, check * XML document against XSD schema restrictions. * @return true if pass, false otherwise */ Datum xmlvalidate_xsd(PG_FUNCTION_ARGS) { #ifdef USE_LIBXML text *data = NULL; unsigned char *xsd = NULL; xmlChar *utf8xsd = NULL; xmltype *xmldata = NULL; char *xmldataint = NULL; xmlChar *xmldatastr = NULL; bool result = false; int lenxml = -1; // length of xml data int lenxsd = -1; // length of xsd data xmlDocPtr doc = NULL; int ret = -1; xmlSchemaParserCtxtPtr ctxt = NULL; xmlSchemaPtr schema = NULL; xmlSchemaValidCtxtPtr validctxt = NULL; // creating xmlChar * from internal XML type xmldata = PG_GETARG_XML_P(0); xmldataint = VARDATA(xmldata); lenxml = VARSIZE(xmldata) - VARHDRSZ; xmldatastr = (xmlChar *) palloc((lenxml + 1) * sizeof(xmlChar)); memcpy(xmldatastr, xmldataint, lenxml); xmldatastr[lenxml] = '\0'; // creating xmlChar* from text representation of XSD data = PG_GETARG_TEXT_P(1); lenxsd = VARSIZE(data) - VARHDRSZ; xsd = (unsigned char*)text_to_cstring(data); //encode XML to internal representation with UTF-8, only one used in LibXML utf8xsd = pg_do_encoding_conversion(xsd, lenxsd, GetDatabaseEncoding(), PG_UTF8); //initialize LibXML structures, if allready done -> do nothing pg_xml_init(); xmlInitParser(); doc = xmlReadMemory((const char*)xmldatastr, lenxml, "include.xml", NULL, 0); if (doc == NULL) { ereport(ERROR, (errcode(ERRCODE_INVALID_XML_DOCUMENT), errmsg("Failed to parse XML document"))); PG_RETURN_BOOL (false); } ctxt = xmlSchemaNewMemParserCtxt((const char*)xsd, lenxsd); if (ctxt == NULL) { // unable to create parser context ereport(ERROR, (errcode(ERRCODE_INVALID_XML_DOCUMENT), errmsg("Error with creating schema, check if XSD schema is valid"))); PG_RETURN_BOOL (false); } schema = xmlSchemaParse(ctxt); // parse schema xmlSchemaFreeParserCtxt(ctxt); // realease parser context validctxt = xmlSchemaNewValidCtxt(schema); if (validctxt == NULL) { // cant create validation context xmlSchemaFree(schema); elog(ERROR, "Cant create validation context"); PG_RETURN_BOOL (false); } // set errors to SQL errors xmlSchemaSetValidErrors(validctxt, xml_error_handler, NULL, stderr); ret = xmlSchemaValidateDoc(validctxt, doc); if (ret == 0) { elog(INFO, "Validates"); result = true; } else if (ret > 0) { elog(INFO, "Dont validates"); result = false; } else { elog(INFO, "Validation generated an internal error"); result = false; } xmlSchemaFree(schema); xmlSchemaFreeValidCtxt(validctxt); xmlFreeDoc(doc); // clean up document in memmory xmlCleanupParser(); // clean up stream parser PG_RETURN_BOOL (result); #else NO_XML_SUPPORT(); PG_RETURN_BOOL (false); #endif }
HRESULT dt_validate(XDR_DT dt, xmlChar const* content) { xmlDocPtr tmp_doc; xmlNodePtr node; xmlNsPtr ns; HRESULT hr; TRACE("(dt:%s, %s)\n", dt_to_str(dt), wine_dbgstr_a((char const*)content)); if (!datatypes_schema) { xmlSchemaParserCtxtPtr spctx; assert(datatypes_src != NULL); spctx = xmlSchemaNewMemParserCtxt((char const*)datatypes_src, datatypes_len); datatypes_schema = Schema_parse(spctx); xmlSchemaFreeParserCtxt(spctx); } switch (dt) { case DT_INVALID: return E_FAIL; case DT_BIN_BASE64: case DT_BIN_HEX: case DT_BOOLEAN: case DT_CHAR: case DT_DATE: case DT_DATE_TZ: case DT_DATETIME: case DT_DATETIME_TZ: case DT_FIXED_14_4: case DT_FLOAT: case DT_I1: case DT_I2: case DT_I4: case DT_I8: case DT_INT: case DT_NMTOKEN: case DT_NMTOKENS: case DT_NUMBER: case DT_R4: case DT_R8: case DT_STRING: case DT_TIME: case DT_TIME_TZ: case DT_UI1: case DT_UI2: case DT_UI4: case DT_UI8: case DT_URI: case DT_UUID: assert(datatypes_schema != NULL); if (content && xmlStrlen(content)) { tmp_doc = xmlNewDoc(NULL); node = xmlNewChild((xmlNodePtr)tmp_doc, NULL, dt_to_str(dt), content); ns = xmlNewNs(node, DT_nsURI, BAD_CAST "dt"); xmlSetNs(node, ns); xmlDocSetRootElement(tmp_doc, node); hr = Schema_validate_tree(datatypes_schema, (xmlNodePtr)tmp_doc); xmlFreeDoc(tmp_doc); } else { /* probably the node is being created manually and has no content yet */ hr = S_OK; } return hr; default: FIXME("need to handle dt:%s\n", dt_to_str(dt)); return S_OK; } }
int main(int argc, char **argv) { int i; int files = 0; xmlSchemaPtr schema = NULL; for (i = 1; i < argc ; i++) { #ifdef LIBXML_DEBUG_ENABLED if ((!strcmp(argv[i], "-debug")) || (!strcmp(argv[i], "--debug"))) debug++; else #endif #ifdef HAVE_SYS_MMAN_H if ((!strcmp(argv[i], "-memory")) || (!strcmp(argv[i], "--memory"))) { memory++; } else #endif if ((!strcmp(argv[i], "-noout")) || (!strcmp(argv[i], "--noout"))) { noout++; } } /*xmlLineNumbersDefault(1);*/ for (i = 1; i < argc ; i++) { if (argv[i][0] != '-') { if (schema == NULL) { xmlSchemaParserCtxtPtr ctxt; #ifdef HAVE_SYS_MMAN_H if (memory) { int fd; struct stat info; const char *base; if (stat(argv[i], &info) < 0) break; if ((fd = open(argv[i], O_RDONLY)) < 0) break; base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ; if (base == (void *) MAP_FAILED) break; ctxt = xmlSchemaNewMemParserCtxt((char *)base,info.st_size); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); munmap((char *) base, info.st_size); } else #endif { /*printf("\n**** CALLING :: xmlSchemaNewParserCtxt argv[i] = %s \n ", argv[i]);*/ printf("\n**** CALLING :: xmlSchemaNewParserCtxt \n "); ctxt = xmlSchemaNewParserCtxt(argv[i]); //ctxt = xmlSchemaNewParserCtxt("/root/Code/libxml2-2.6.15/ixml/basic/memory_test.xsd"); printf("\n**** CALLING :: xmlSchemaParse \n "); xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); printf("\n**** CALLING :: xmlSchemaParse \n "); schema = xmlSchemaParse(ctxt); xmlSchemaFreeParserCtxt(ctxt); } #if 0 #ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_DEBUG_ENABLED if (debug) xmlSchemaDump(stdout, schema); #endif #endif /* LIBXML_OUTPUT_ENABLED */ #endif /*#if 0*/ if (schema == NULL) goto failed_schemas; } else { IXML_Document *doc; printf("\n ***** CALLING :: xmlReadFile:> %s ", argv[i]); //doc = xmlReadFile(argv[i],NULL,0); //doc = ixmlLoadDocument("/root/Code/libxml2-2.6.15/ixml/basic/memory_test.xml"); doc = ixmlLoadDocument(argv[i]); #if 0 printf("nodeName = %s\n",doc->n.firstChild->nodeName); printf("firstAttr->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeName); printf("firstAttr->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeValue); printf("firstAttr->nextSibling->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeName); printf("firstAttr->nextSibling->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeValue); #endif if (doc == NULL) { fprintf(stderr, "Could not parse %s\n", argv[i]); } else { xmlSchemaValidCtxtPtr ctxt; int ret; printf("\n ***** CALLING :: xmlSchemaNewValidCtxt *****\n "); ctxt = xmlSchemaNewValidCtxt(schema); printf("\n ***** CALLING :: xmlSchemaSetValidErrors *****\n "); xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr); ret = xmlSchemaValidateDoc(ctxt, doc); #if 0 printf("nodeName = %s\n",doc->n.firstChild->nodeName); printf("firstAttr->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeName); printf("firstAttr->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nodeValue); printf("firstAttr->nextSibling->nodeName = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeName); printf("firstAttr->nextSibling->nodeValue = %s\n",doc->n.firstChild->firstChild->firstAttr->nextSibling->nodeValue); #endif if (ret == 0) { printf("%s validates\n", argv[i]); } else if (ret > 0) { printf("%s fails to validate\n", argv[i]); } else { printf("%s validation generated an internal error\n", argv[i]); } xmlSchemaFreeValidCtxt(ctxt); ixmlDocument_free(doc); } } files ++; } } if (schema != NULL) xmlSchemaFree(schema); if (files == 0) { printf("Usage : %s [--debug] [--noout] schemas XMLfiles ...\n", argv[0]); printf("\tParse the HTML files and output the result of the parsing\n"); #ifdef LIBXML_DEBUG_ENABLED printf("\t--debug : dump a debug tree of the in-memory document\n"); #endif printf("\t--noout : do not print the result\n"); #ifdef HAVE_SYS_MMAN_H printf("\t--memory : test the schemas in memory parsing\n"); #endif } failed_schemas: /*printf("\n**** failed_schemas\n");*/ xmlSchemaCleanupTypes(); /*xmlCleanupParser(); xmlResetLastError(); xmlMemoryDump();*/ return(0); }