How to use the lxml.etree.XMLSchema function in lxml

To help you get started, we’ve selected a few lxml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vaclavcadek / scikit2pmml / tests / generic.py View on Github external
def _validate_against_schema(schema, pmml):
        with open(schema, 'r') as f:
            schema_root = etree.XML(f.read())
        schema = etree.XMLSchema(schema_root)
        parser = etree.XMLParser(schema=schema)
        etree.fromstring(ET.tostring(pmml.getroot(), encoding='utf-8', method='xml'), parser)
github mosdef-hub / foyer / foyer / validator.py View on Github external
def validate_xsd(ff_tree, xsd_file=None):
        """ Check consistency with forcefields/ff.xsd """
        if xsd_file is None:
            xsd_file = join(split(abspath(__file__))[0], 'forcefields', 'ff.xsd')

        xmlschema_doc = etree.parse(xsd_file)
        xmlschema = etree.XMLSchema(xmlschema_doc)

        error_texts = {'missing_atom_type_in_nonbonded':
                           ("Atom type {} is found in NonbondedForce at line {}"
                            " but undefined in AtomTypes"),
                       'nonunique_atomtype_name':
                           "Atom type {} is defined a second time at line {}",
                       'atomtype_name_key':
                           "Atom type {} is defined a second time at line {}"
        }

        def create_error(keyword, message, line):
            atomtype = message[message.find("[") + 1:message.find("]")]
            error_text = error_texts[keyword].format(atomtype, line)
            return ValidationError(error_text, ex, line)

        try:
github geopython / pycsw / sbin / validate_xml.py View on Github external
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# =================================================================

import sys

from lxml import etree

if len(sys.argv) < 3:
    print 'Usage: %s  ' % sys.argv[0]
    sys.exit(1)

print 'Validating %s against schema %s' % (sys.argv[1], sys.argv[2])

SCHEMA = etree.XMLSchema(etree.parse(sys.argv[2]))
PARSER = etree.XMLParser(schema=SCHEMA)

try:
    VALID = etree.parse(sys.argv[1], PARSER)
    print 'Valid XML document'
except Exception, err:
    print 'ERROR: %s' % str(err)
github scanny / python-pptx / lab / parse_xsd / validate.py View on Github external
test_path = '../../../ar-fy-plans/test/ppt/slideLayouts'

xmlschema = etree.XMLSchema(etree.parse('xsd/pml.xsd'))  # more compact form

for idx in range(1, 29):
    print 'slideLayout%d.xml' % idx
    slideLayout_path = os.path.join(test_path, 'slideLayout%d.xml' % idx)
    sldLayout = etree.parse(slideLayout_path)
    xmlschema.assert_(sldLayout)

sys.exit()


# assemble the necessary items
xmlschema = etree.XMLSchema(etree.parse('xsd/pml.xsd'))  # more compact form
test_path = '../../../ar-fy-plans/test/ppt/slides'
slide_path = os.path.join(test_path, 'slide1.xml')
sld = etree.parse(slide_path)  # should be ElementTree, not Element

# get valid True/False, no message
valid = xmlschema.validate(sld)
# print "valid => %s" % valid

# print out validation log for messages
# if not valid:
#     log = xmlschema.error_log
#     print type(log)
#     print(log.last_error)

# if not valid:
for e in xmlschema.error_log:
github fp7-ofelia / ocf / optin_manager / src / python / openflow / optin_manager / sfa / trust / credential.py View on Github external
def verify(self, trusted_certs=None, schema=None, trusted_certs_required=True):
        if not self.xml:
            self.decode()

        # validate against RelaxNG schema
        if HAVELXML and not self.legacy:
            if schema and os.path.exists(schema):
                tree = etree.parse(StringIO(self.xml))
                schema_doc = etree.parse(schema)
                
                xmlschema = etree.XMLSchema(schema_doc)
                #except Exception as e:
                #    print e
                if not xmlschema:#.validate(tree):
                    error = xmlschema.error_log.last_error
                    message = "%s: %s (line %s)" % (self.get_summary_tostring(), error.message, error.line)
                    raise CredentialNotVerifiable(message)

        if trusted_certs_required and trusted_certs is None:
            trusted_certs = []

#       trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
        trusted_cert_objects = []
        ok_trusted_certs = []
        # If caller explicitly passed in None that means skip cert chain validation.
        # Strange and not typical
        if trusted_certs is not None:
github dursobr / Pythics / pythics / html.py View on Github external
def open_file(self, filename):
        self.frame.hide()
        # load and parse the file
        if lxml_loaded:
            parser = ElementTree.ETCompatXMLParser()
            self.tree = ElementTree.parse(filename, parser=parser)
        else:
            self.tree = ElementTree.parse(filename)
        # validate the file if lxml is available
        if lxml_loaded:
            xmlschema_tree = ElementTree.parse(xmlschema_f)
            xmlschema = ElementTree.XMLSchema(xmlschema_tree)
            xmlschema.assertValid(self.tree)
        root = self.tree.getroot()
        self.layout(root, list(), self.main_sizer)
        self.frame.show()
        return self.anonymous_controls, self.controls
github ome / openmicroscopy / Xml / Validator / WebApp / validator / OmeValidator.py View on Github external
else:
					if self.theNamespace == "http://www.openmicroscopy.org/Schemas/OME/2008-09":
						# use September 2008 schema
						self.theSchemaFile = "ome-2008-09-V1.xsd"
					else:
						if self.theNamespace == "http://www.openmicroscopy.org/Schemas/OME/2009-09":
							# use September 2009 schema
							self.theSchemaFile = "ome-2009-09-V1.xsd"
						else:
							if self.theNamespace == "http://www.openmicroscopy.org/Schemas/OME/2010-04":
								# use September 2009 schema
								self.theSchemaFile = "ome-2010-04-V1.xsd"
		
		# loading the OME schema to validate against
		try:
			schema = etree.XMLSchema(etree.parse(schemaFilePath(self.theSchemaFile)))
		except:
			# chosen schema failed to laod
			self.errorList.append(ParseMessage(None, None, None, "XSD", None, "Validator Internal error: XSD schema file could not be found [1]"))
			schema = None;
			
		return schema
github ncqgm / gnumed / gnumed / gnumed / client / wxpython / gmEMRTimelineWidgets.py View on Github external
def _validate_timeline_file(self, tl_filename):
		xsd_name = 'timeline.xsd'
		xsd_paths = [
			os.path.join(gmTools.gmPaths().system_app_data_dir, 'resources', 'timeline', xsd_name),
			# maybe in dev tree
			os.path.join(gmTools.gmPaths().local_base_dir, 'resources', 'timeline', xsd_name)
		]
		xml_schema = None
		for xsd_filename in xsd_paths:
			_log.debug('XSD: %s', xsd_filename)
			if not os.path.exists(xsd_filename):
				_log.warning('not found')
				continue
			try:
				xml_schema = lxml_etree.XMLSchema(file = xsd_filename)
				break
			except lxml_etree.XMLSchemaParseError:
				_log.exception('cannot parse')
		if xml_schema is None:
			_log.error('no XSD found')
			return False

		with open(tl_filename, encoding = 'utf-8') as tl_file:
			try:
				xml_doc = lxml_etree.parse(tl_file)
			except lxml_etree.XMLSyntaxError:
				_log.exception('[%s] does not parse as XML', tl_filename)
				return False

		if xml_schema.validate(xml_doc):
			_log.debug('[%s] seems valid', tl_filename)
github gvSIGAssociation / gvsig-online / gvsigol / gvsigol_symbology / sld.py View on Github external
localschema = open(localschema.name, 'rt')
            self._schemadoc = parse(localschema)
            localschema.close()

            StyledLayerDescriptor._cached_schema = localschema.name
        else:
            logging.debug('Fetching schema from cache.')

            localschema = open(StyledLayerDescriptor._cached_schema, 'rt')
            self._schemadoc = parse(localschema)
            localschema.close()

        if not sld_file is None:
            self._node = parse(sld_file)
            self._schema = XMLSchema(self._schemadoc)
            if not self._schema.validate(self._node):
                logging.warn('SLD File "%s" does not validate against the SLD schema.', sld_file)
        else:
            self._node = Element("{%s}StyledLayerDescriptor" % SLDNode._nsmap['sld'], version="1.0.0", nsmap=SLDNode._nsmap)
            self._schema = None

        setattr(self.__class__, 'NamedLayer', SLDNode.makeproperty('sld', cls=NamedLayer,
                docstring="The named layer of the SLD."))
github obspy / obspy / obspy / io / stationxml / core.py View on Github external
"""
    Checks if the given path is a valid StationXML file.

    Returns a tuple. The first item is a boolean describing if the validation
    was successful or not. The second item is a list of all found validation
    errors, if existent.

    :param path_or_object: File name or file like object. Can also be an etree
        element.
    """
    # Get the schema location.
    schema_location = os.path.dirname(inspect.getfile(inspect.currentframe()))
    schema_location = os.path.join(schema_location, "data",
                                   "fdsn-station-1.0.xsd")

    xmlschema = etree.XMLSchema(etree.parse(schema_location))

    if isinstance(path_or_object, etree._Element):
        xmldoc = path_or_object
    else:
        try:
            xmldoc = etree.parse(path_or_object)
        except etree.XMLSyntaxError:
            return (False, ("Not a XML file.",))

    valid = xmlschema.validate(xmldoc)

    # Pretty error printing if the validation fails.
    if valid is not True:
        return (False, xmlschema.error_log)
    return (True, ())