Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple errors validating XML file with Python libraries?

I have some XML file i want to validate and i have to do it with Python. I've tryed to validate it with XSD with lxml. But i get only one error which occurs first but i need all errors and mismatches in XML file. Is there any method how i can manage to get list of all errors with lxml? Or are there any other Python solutions?

like image 869
Alice Avatar asked Jun 15 '26 12:06

Alice


2 Answers

The way to solve this problem was:

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

May be there are better ways to solve this problem :)

like image 132
Alice Avatar answered Jun 18 '26 02:06

Alice


With lxml, you can iterate over error_log and print line number and error message for each error:

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))
like image 34
Roger Dahl Avatar answered Jun 18 '26 00:06

Roger Dahl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!