本文整理汇总了Python中lxml.etree.XMLSchema方法的典型用法代码示例。如果您正苦于以下问题:Python etree.XMLSchema方法的具体用法?Python etree.XMLSchema怎么用?Python etree.XMLSchema使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lxml.etree
的用法示例。
在下文中一共展示了etree.XMLSchema方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: xsd
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def xsd(self, xsd, filename):
"""
Look at schema, validation, conform, structure, content, etc...
Code for 1.7.1
"""
# syntax check against XSD for file format
schema = etree.XMLSchema(file=xsd)
parser = objectify.makeparser(schema = schema)
tree = etree.parse(filename)
root = tree.getroot()
database = objectify.fromstring(etree.tostring(root, encoding="UTF-8"), parser)
LOG.info(_('Matches XSD schema.'))
#dump = objectify.dump(database)
#print(dump)
示例2: test_validate_alto
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def test_validate_alto(self):
"""
Validate ALTO
"""
fp = StringIO.StringIO()
id = self.record.add_respstmt('recognition', 'baz')
self.record.add_segment((0, 0, 0, 0), language='foo', confidence=80)
self.record.add_graphemes([{'bbox': (0, 0, 0, 0),
'confidence': 95,
'grapheme': ' '}])
self.record.add_segment((0, 0, 0, 0), language='foo', confidence=80)
self.record.add_graphemes([{'bbox': (0, 0, 0, 0),
'confidence': 95,
'grapheme': 'AB'}])
self.record.add_choices('line_11', [{'confidence': 95,
'alternative': ''.join(x)} for x in itertools.permutations('ABCD', 2)])
self.record.write_alto(fp)
doc = etree.fromstring(fp.getvalue())
with open(os.path.join(resources, 'alto-3-1.xsd')) as schema_fp:
alto_schema = etree.XMLSchema(etree.parse(schema_fp))
alto_schema.assertValid(doc)
示例3: parse
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def parse(self, filename):
self.parser = None
# find parser
try:
from lxml.etree import parse, XMLSchema
self.logger.info('using lxml.etree parser')
# parse XML and validate it
tree = parse(filename)
# get XSD
schemaDoc = parse(XSDContents)
schema = XMLSchema(schemaDoc)
if schema.validate(tree):
self.logger.info('XML validated')
return tree
print >> stderr, schema.error_log
raise ValueError('XML NOT validated: {}'.format(filename))
except ImportError:
try:
from xml.etree.ElementTree import parse
self.logger.info('using xml.etree.ElementTree parser')
return parse(filename)
except ImportError:
self.logger.critical("Failed to import ElementTree from any known place")
raise
示例4: xml_to_xsd_validation
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def xml_to_xsd_validation(file_xml, file_xsd):
""" Verify that the XML compliance with XSD
Arguments:
1. file_xml: Input xml file
2. file_xsd: xsd file which needs to be validated against xml
Return:
No return value
"""
try:
print_info("Validating:{0}".format(file_xml))
print_info("xsd_file:{0}".format(file_xsd))
xml_doc = parse(file_xml)
xsd_doc = parse(file_xsd)
xmlschema = XMLSchema(xsd_doc)
xmlschema.assert_(xml_doc)
return True
except XMLSyntaxError as err:
print_error("PARSING ERROR:{0}".format(err))
return False
except AssertionError, err:
print_error("Incorrect XML schema: {0}".format(err))
return False
示例5: validar
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def validar(self):
arquivo_esquema = self.caminho_esquema + self.arquivo_esquema
# Aqui é importante remover a declaração do encoding
# para evitar erros de conversão unicode para ascii
xml = tira_abertura(self.xml).encode(u'utf-8')
esquema = etree.XMLSchema(etree.parse(arquivo_esquema))
if not esquema.validate(etree.fromstring(xml)):
for e in esquema.error_log:
if e.level == 1:
self.alertas.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))
elif e.level == 2:
self.erros.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', ''))
return esquema.error_log
示例6: GenerateParser
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def GenerateParser(factory, xsdstring):
"""
This function generate a xml parser from a class factory
"""
parser = XMLClassParser(strip_cdata=False, remove_blank_text=True)
factory.Parser = parser
ComputedClasses = factory.CreateClasses()
if factory.FileName is not None:
ComputedClasses = ComputedClasses[factory.FileName]
BaseClass = [(name, XSDclass) for name, XSDclass in ComputedClasses.items() if XSDclass.IsBaseClass]
parser.initMembers(
factory.NSMAP,
factory.etreeNamespaceFormat,
BaseClass[0] if len(BaseClass) == 1 else None,
etree.XMLSchema(etree.fromstring(xsdstring)))
class_lookup = XMLElementClassLookUp(factory.ComputedClassesLookUp)
parser.set_element_class_lookup(class_lookup)
return parser
示例7: check_schema
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def check_schema(self, path, title):
try:
etree.XMLSchema(etree.parse(self.filepath(path)))
except Exception as e:
message = "XSD schema %s at `%s` is not valid. Errors: %s" % (
title,
path,
repr(e),
)
raise exceptions.InvalidSchemaException(self.repo, message)
示例8: _is_valid
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def _is_valid(cls, xml, xsd_filepath, xsd_name):
'''Returns whether or not an XML file is valid according to
an XSD. Returns a tuple, the first value is a boolean indicating
whether the validation passed or not. The second is a list of tuples,
each containing the error message and the error line.
Params:
xml - etree of the XML to be validated
xsd_filepath - full path to the XSD file
xsd_name - string describing the XSD
Returns:
(is_valid, [(error_message_string, error_line_number)])
'''
xsd = etree.parse(xsd_filepath)
schema = etree.XMLSchema(xsd)
# With libxml2 versions before 2.9, this fails with this error:
# gmx_schema = etree.XMLSchema(gmx_xsd)
# File "xmlschema.pxi", line 103, in
# lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:116069)
# XMLSchemaParseError: local list type: A type, derived by list or
# union, must have the simple ur-type definition as base type,
# not '{http://www.opengis.net/gml/3.2}doubleList'., line 118
try:
schema.assertValid(xml)
except etree.DocumentInvalid:
log.info(
'Validation errors found using schema {0}'.format(xsd_name))
errors = []
for error in schema.error_log:
errors.append((error.message, error.line))
errors.insert
return False, errors
return True, []
示例9: dissemin_xsd_1_0
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def dissemin_xsd_1_0():
'''
Loads dissemin xsd and prepares it as schema ready for validation.
'''
testdir = os.path.dirname(os.path.abspath(__file__))
dissemin_xsd = etree.parse(os.path.join(testdir, 'schema','dissemin_v1.0.xsd'))
return etree.XMLSchema(dissemin_xsd)
示例10: mets_xsd
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def mets_xsd():
"""
Returns a mets xsd as schema ready to validate
"""
return etree.XMLSchema(etree.parse("http://www.loc.gov/standards/mets/version112/mets.xsd"))
示例11: mods_3_7_xsd
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def mods_3_7_xsd():
'''
Loads mods 3.7 xsd and prepares it as schema ready for validation.
'''
mods_xsd = etree.parse("http://www.loc.gov/standards/mods/v3/mods-3-7.xsd")
return etree.XMLSchema(mods_xsd)
示例12: test_validate_xsd
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def test_validate_xsd(self):
'''
Validates dissemin xml schema against xml schema
'''
xmlschema = etree.XMLSchema(etree.parse("http://www.w3.org/2001/XMLSchema.xsd"))
testdir = os.path.dirname(os.path.abspath(__file__))
dissemin_xsd = etree.parse(os.path.join(testdir, 'dissemin_v1.0.xsd'))
xmlschema.assertValid(dissemin_xsd)
示例13: verify
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def verify(self, node):
"""
verifies a signature
:param node: Signature node
:type node: lxml.etree.Element
:return:
"""
schema = etree.XMLSchema(
etree.parse(path.join(path.dirname(__file__), "data/XAdES.xsd"))
)
schema.assertValid(node)
signed_properties = node.find(
"ds:Object/etsi:QualifyingProperties["
"@Target='#{}']/etsi:SignedProperties".format(node.get("Id")),
namespaces=NS_MAP,
)
assert signed_properties is not None
self.calculate_signed_properties(signed_properties, node, False)
unsigned_properties = node.find(
"ds:Object/etsi:QualifyingProperties["
"@Target='#{}']/etsi:UnSignedProperties".format(node.get("Id")),
namespaces=NS_MAP,
)
if unsigned_properties is not None:
self.calculate_unsigned_properties(signed_properties, node, False)
policy_id = signed_properties.find(
"etsi:SignedSignatureProperties/etsi:SignaturePolicyIdentifier/"
"etsi:SignaturePolicyId/etsi:SigPolicyId/etsi:Identifier",
namespaces=NS_MAP,
)
policy = self.policies[None]
if policy_id is not None:
if policy_id.text in self.policies:
policy = self.policies[policy_id.text]
policy.validate(node)
res = super(XAdESContext, self).verify(node)
return res
示例14: schema
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def schema(cls):
if cls._schema is None:
schema_path = os.path.join(os.path.dirname(__file__), "..", "schemas", cls.schema_file)
cls._schema = etree.XMLSchema(etree.parse(schema_path))
return cls._schema
示例15: validate
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import XMLSchema [as 别名]
def validate(tree):
schema = ET.XMLSchema(file=of_config.OF_CONFIG_1_1_1_XSD)
if not schema(tree):
print(schema.error_log)