3

我有一些要验证的 XML 文件,我必须使用 Python 来验证。我尝试使用带有 lxml 的 XSD 验证它。但是我只得到一个首先发生的错误,但我需要 XML 文件中的所有错误和不匹配。有什么方法可以让我使用 lxml 获取所有错误的列表吗?或者还有其他 Python 解决方案吗?

4

6 回答 6

6

解决这个问题的方法是:

try:
    xmlschema.assertValid(xml_to_validate)
except etree.DocumentInvalid, xml_errors:
    pass
print "List of errors:\r\n", xml_errors.error_log

可能有更好的方法来解决这个问题:)

于 2012-07-23T11:18:58.373 回答
2

使用lxml,您可以迭代error_log并打印每个错误的行号和错误消息:

def validate_with_lxml(xsd_tree, xml_tree):
    schema = lxml.etree.XMLSchema(xsd_tree)
    try:
        schema.assertValid(xml_tree)
    except lxml.etree.DocumentInvalid:
        print("Validation error(s):")
        for error in schema.error_log:
            print("  Line {}: {}".format(error.line, error.message))
于 2019-06-26T17:03:21.130 回答
2

使用XMLSchema库,您可以使用以下iter_errors方法:https ://xmlschema.readthedocs.io/en/latest/api.html?highlight=iter_errors#xmlschema.XMLSchemaBase.iter_errors

这是我的代码(Python 3):

def get_validation_errors(xml_file, xsd_uri='example.xsd'):
    xml_string = xml_file.read().decode('utf-8')
    dir_path = os.path.dirname(os.path.realpath(__file__))
    xsd_path = os.path.join(dir_path, xsd_uri)
    schema = xmlschema.XMLSchema(xsd_path)
    validation_error_iterator = schema.iter_errors(xml_string)
    for idx, validation_error in enumerate(validation_error_iterator, start=1):
        print(f'[{idx}] path: {validation_error.path} | reason: {validation_error.reason}')
于 2020-10-18T18:36:35.263 回答
1

您可以 阅读有关错误异常的 Python 文档以了解如何执行try/except设计模式,并且在该except部分中您可以存储不匹配项(例如列表或对列表),然后从后面try/except的点再次递归第一个错误。让我知道这是否不够描述。

干杯!

于 2012-07-20T18:28:17.857 回答
0

由于几个错误,提供的解决方案不再起作用。在 xmlschema 上应用 assertValid 之前,您必须按如下方式指定它:

try:
   xmlschema_doc = lxml.etree.parse(filename)
   xmlschema = lxml.etree.XMLSchema(xmlschema_doc)
   xmlschema.assertValid(elem_tree)
except lxml.etree.ParseError as e:
   raise lxml.etree.ParserError(str(e))
except lxml.etree.DocumentInvalid as e:
   if ignore_errors:
    raise lxml.etree.ValidationError("The Config tree is invalid with error 
       message:\n\n" + str(e)) 
于 2018-06-29T11:18:23.423 回答
0
def get_validation_errors(xml_file, xsd_file):
    schema = xmlschema.XMLSchema(xsd_file)
    validation_error_iterator = schema.iter_errors(xml_file)
    errors = list()
    for idx, validation_error in enumerate(validation_error_iterator, start=1):
        errors.append(validation_error.__str__())
        print(
            f'[{idx}] path: {validation_error.path} | reason: {validation_error.reason} | message: {validation_error.message}')
    return errors
于 2021-06-23T07:25:07.697 回答