Apart from the built-in DTD support in parsers, lxml currently supports three schema languages: DTD, Relax NG and XML Schema. All three provide identical APIs in lxml, represented by validator classes with the obvious names.
lxml also provides support for ISO-Schematron, based on the pure-XSLT skeleton implementation of Schematron:
There is also basic support for pre-ISO-Schematron through the libxml2 Schematron features. However, this does not currently support error reporting in the validation phase due to insufficiencies in the implementation as of libxml2 2.6.30.
The usual setup procedure:
>>> from lxml import etree
The parser in lxml can do on-the-fly validation of a document against a DTD or an XML schema. The DTD is retrieved automatically based on the DOCTYPE of the parsed document. All you have to do is use a parser that has DTD validation enabled:
>>> parser = etree.XMLParser(dtd_validation=True)
Obviously, a request for validation enables the DTD loading feature. There are two other options that enable loading the DTD, but that do not perform any validation. The first is the load_dtd keyword option, which simply loads the DTD into the parser and makes it available to the document as external subset. You can retrieve the DTD from the parsed document using the docinfo property of the result ElementTree object. The internal subset is available as internalDTD, the external subset is provided as externalDTD.
The third way to activate DTD loading is with the attribute_defaults option, which loads the DTD and weaves attribute default values into the document. Again, no validation is performed unless explicitly requested.
XML schema is supported in a similar way, but requires an explicit schema to be provided:
>>> schema_root = etree.XML('''\ ... <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> ... <xsd:element name="a" type="xsd:integer"/> ... </xsd:schema> ... ''') >>> schema = etree.XMLSchema(schema_root) >>> parser