Validating an XML File with LXML

I've been playing with XML files recently and have on the odd occasion needed to validate a file against an XML schema. This is surprisingly easy using lxml, the Swiss Army knife of Python XML processing. Allow me to demonstrate.

>>> from lxml import etree

>>> schema = etree.XMLSchema(etree.parse('schema_file_name.xsd'))

>>> xml_file = etree.parse('xml_file_name.xml')

>>> schema.validate(xml_file)


Job done. If you are unlucky enough that your file doesn't validate you can find out by checking the error_log attribute of your XMLSchema object.