def revalidate(self): """ Re-validate the in memory object tree against the related XSD """ xmlBuffer = self.__write_xml(self.configuration, StringIO()) xml = xmlBuffer.getvalue() xmlBuffer.close() xsdBuffer = open(self.xsdFile, 'r') xsd = "".join(xsdBuffer.readlines()) xsdBuffer.close() try: # Validate the config file cwd = os.path.sep.join(self.xmlFile.split(os.path.sep)[:-1]) os.chdir(cwd) self.logger.debug("Validating XML against XSD") pyxsval.parseAndValidateXmlInputString( inputText=xml, xsdText=xsd, validateSchema=1, **Objectify.KWARGS) except Exception: self.logger.error("Error occurred within %s" % cwd) raise InvalidConfigurationXML(format_exc()) finally: os.chdir(self.cwd) self.logger.debug("Validated XML against XSD")
def validateXML(file_cho): file_chosen = ''.join(x for x in file_cho) with open("WorldCrisis.xsd.xml", "r") as f: xsd = ''.join(x for x in f.readlines()) try: pyxsval.parseAndValidateXmlInputString(file_chosen, xsdText=xsd, validateSchema=0) #if XML file did not follow the schema except pyxsval.XsvalError, errstr: return False
def validatexml(xml_string): """"" # validatexml # attempts to parse and validate xml file # input: xml string to parse and validate # output: a string with either "Validation Complete" or "Validation aborted: " followed by error details on validation failure # Note: For performance gains, schema file is assumed to be valid, # this validator makes use of modules minixsv and genxmlif, for more info see the README's in folders /minixsv/ and /genxmlif/ """"" assert type(xml_string) is StringType, 'validatexml(xml_string): xml_string is not type string' # get xml schema try: f = open("wc/WC2.xsd", 'r') strxsd = f.read() except IOError: print 'could not open schema WC2.xsd, make sure there is a valid schema located in /wc' # call validator try: elementTreeWrapper = pyxsval.parseAndValidateXmlInputString(xml_string, xsdText= strxsd, xmlIfClass= pyxsval.XMLIF_ELEMENTTREE, validateSchema=0) return "Validation Complete" except pyxsval.XsvalError, err: sys.stderr.write(str(err)) return "Validation aborted: " + str(err)
def clean(self): super(XmlUploadForm, self).clean() if not self['xml'].value(): # the 'required' part of the xml attrribute will report the error return try: ret = parseAndValidateXmlInputString( inputText=self['xml'].value().read(), xsdText=XSD) except Exception as e: raise forms.ValidationError('XML is invalid:\n' + e.message)
def validate_xml(results_xml): """ @type results_xml: C{str} @param results_xml: The results xml Postprocess the element """ results_xsd = open(SCHEMA_FILENAME).read() etw = xsv.parseAndValidateXmlInputString(results_xml, xsdText = results_xsd) etw.getTree()
def validXML (xml_instance, xml_schema_filename): """Validates an instance against the provided schema. Returns True if valid, else False""" assert(xml_instance is not None) assert(xml_schema_filename is not None) try: etw = xsv.parseAndValidateXmlInputString(xml_instance, xml_schema_filename,xmlIfClass=xsv.XMLIF_ELEMENTTREE) et = etw.getTree() root = et.getroot() return True except: pass return False
def post(self): xmlfile = self.request.get("data") xmlschema = getSchemaString() # validate XML instance try: # call validator elementTreeWrapper = pyxsval.parseAndValidateXmlInputString (xmlfile, xsdText=str(xmlschema), verbose=0) #elementtree object after validation elemTree = elementTreeWrapper.getTree() except pyxsval.XsvalError, errstr: self.redirect('/import?msg=validation') return
def post(self): xmlText = self.request.get('xml_input') unicode_content = xmlText.decode('utf-8') xmlText = unicode_content.encode('ascii', 'xmlcharrefreplace') xml_filename = self.request.params['xml_input'].filename #if file is empty if(0 == len(xml_filename)): render_status_page("Error!", "No file chosen!", "Please try again with a file selected.", "error", self) return #if file is not a schame .xml file elif(not xml_filename.endswith('.xml')): render_status_page("Error!", "Improper file chosen!", "Please try again with the proper .xml file.", "error", self) return #otherwise its all good else: q = Schema.all() schema_object = q.get() try : xsd = schema_object.schema except AttributeError : render_status_page("Error!", "No Schema Present!", "Schema is not uploaded. Please first run import schema with the appropriate password.", "error", self) return try : validation_info = pyxsval.parseAndValidateXmlInputString((xmlText), (xsd)) except pyxsval.XsvalError, errstr: render_status_page("Error!", "File is not Schema-Compliant", 'The XML file doesn\'t match the schema: %s' % errstr, "error", self) return except GenXmlIfError, errstr: render_status_page("Error!", "File is not Schema-Compliant", 'The XML file didn\'t parse: %s' % errstr, "error", self) return
def RunValidation(xml_file, schema_file=None, verbose=True): """Run the validation process and return a message with the result. Args: xml_file: An XML input file schema_file: A DSPL schema file; if not given, the default 'dspl.xsd' is used. verbose: Include helpful, extra information about validation Returns: String containing result of validation process """ result = '' xml_file_text = xml_file.read() if schema_file: schema_file_text = schema_file.read() else: schema_file = open(os.path.join(_SCHEMA_PATH, _DSPL_SCHEMA_FILE), 'r') schema_file_text = schema_file.read() schema_file.close() # Insert proper paths into XSD schemaLocation tags substitution_function = (lambda m: 'schemaLocation="%s"' % os.path.join( _SCHEMA_PATH, m.group(1))) schema_file_text = re.sub('schemaLocation="([a-zA-Z_0-9.]+)"', substitution_function, schema_file_text, 2) # Figure out which type of parsing exception this version of ElementTree # throws; code adapted from example in ElementTree documentation try: parse_error = xml.etree.ElementTree.ParseError except AttributeError: try: xml.etree.ElementTree.XML('<foo>') except: from sys import exc_type as parse_error try: pyxsval.parseAndValidateXmlInputString( xml_file_text, xsdText=schema_file_text, xmlIfClass=pyxsval.XMLIF_ELEMENTTREE, warningProc=pyxsval.PRINT_WARNINGS) except (GenXmlIfError, parse_error) as xml_error: # XML parsing error error_string = str(xml_error) if verbose: result = ('Input is not valid XML\n\n%s\n%s' % (error_string, GetErrorContext(xml_file_text, GetErrorLineNumber(error_string)))) else: result = error_string except pyxsval.XsvalError as schema_error: # Schema validation error error_string = str(schema_error) if verbose: result = ('Input does not validate against DSPL schema\n\n%s\n%s' % (error_string, GetErrorContext(xml_file_text, GetErrorLineNumber(error_string)))) else: result = error_string else: if verbose: result = 'XML file validates successfully!' return result
def test_export_validation(self): xml = to_xml.convert() ret = parseAndValidateXmlInputString(inputText=xml, xsdText=XSD) self.assertTrue(not not ret)
def RunValidation(xml_file, schema_file=None, verbose=True): """Run the validation process and return a message with the result. Args: xml_file: An XML input file schema_file: A DSPL schema file; if not given, the default 'dspl.xsd' is used. verbose: Include helpful, extra information about validation Returns: String containing result of validation process """ result = '' xml_file_text = xml_file.read() if schema_file: schema_file_text = schema_file.read() else: schema_file = open(os.path.join(_SCHEMA_PATH, _DSPL_SCHEMA_FILE), 'r') schema_file_text = schema_file.read() schema_file.close() # Insert proper paths into XSD schemaLocation tags substitution_function = ( lambda m: 'schemaLocation="%s"' % os.path.join(_SCHEMA_PATH, m.group(1))) schema_file_text = re.sub( 'schemaLocation="([a-zA-Z_0-9.]+)"', substitution_function, schema_file_text, 2) # Figure out which type of parsing exception this version of ElementTree # throws; code adapted from example in ElementTree documentation try: parse_error = xml.etree.ElementTree.ParseError except AttributeError: try: xml.etree.ElementTree.XML('<foo>') except: from sys import exc_type as parse_error try: pyxsval.parseAndValidateXmlInputString( xml_file_text, xsdText=schema_file_text, xmlIfClass=pyxsval.XMLIF_ELEMENTTREE, warningProc=pyxsval.PRINT_WARNINGS) except (GenXmlIfError, parse_error) as xml_error: # XML parsing error error_string = str(xml_error) if verbose: result = ('Input is not valid XML\n\n%s\n%s' % (error_string, GetErrorContext( xml_file_text, GetErrorLineNumber(error_string)))) else: result = error_string except pyxsval.XsvalError as schema_error: # Schema validation error error_string = str(schema_error) if verbose: result = ('Input does not validate against DSPL schema\n\n%s\n%s' % (error_string, GetErrorContext( xml_file_text, GetErrorLineNumber(error_string)))) else: result = error_string else: if verbose: result = 'XML file validates successfully!' return result
def handle(self, *args, **options): parseAndValidateXmlInputString( inputText=sys.stdin.read(), xsdText=XSD)