Apart from the built-in DTD support in parsers, lxml currently supports threeschema languages:DTD,Relax NG andXML Schema. All three provideidentical APIs in lxml, represented by validator classes with the obviousnames.
lxml also provides support for ISO-Schematron, based on the pure-XSLTskeleton implementation of Schematron:
There is also basic support forpre-ISO-Schematron through the libxml2Schematron features. However, this does not currently support error reportingin the validation phase due to insufficiencies in the implementation as oflibxml2 2.6.30.
The usual setup procedure:
>>>fromlxmlimportetree
The parser in lxml can do on-the-fly validation of a document againsta DTD or an XML schema. The DTD is retrieved automatically based onthe DOCTYPE of the parsed document. All you have to do is use aparser 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 donot perform any validation. The first is theload_dtd keywordoption, which simply loads the DTD into the parser and makes itavailable to the document as external subset. You can retrieve theDTD from the parsed document using thedocinfo property of theresult ElementTree object. The internal subset is available asinternalDTD, the external subset is provided asexternalDTD.
The third way to activate DTD loading is with theattribute_defaults option, which loads the DTD and weavesattribute default values into the document. Again, no validation isperformed unless explicitly requested.
XML schema is supported in a similar way, but requires an explicitschema 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=etree.XMLParser(schema=schema)>>>root=etree.fromstring("<a>5</a>",parser)
If the validation fails (be it for a DTD or an XML schema), the parserwill raise an exception:
>>>root=etree.fromstring("<a>no int</a>",parser)# doctest: +ELLIPSISTraceback (most recent call last):lxml.etree.XMLSyntaxError:Element 'a': 'no int' is not a valid value of the atomic type 'xs:integer'...
If you want the parser to succeed regardless of the outcome of thevalidation, you should use a non validating parser and run thevalidation separately after parsing the document.
As described above, the parser support for DTDs depends on internal orexternal subsets of the XML file. This means that the XML file itselfmust either contain a DTD or must reference a DTD to make this work.If you want to validate an XML document against a DTD that is notreferenced by the document itself, you can use theDTD class.
To use theDTD class, you must first pass a filename or file-like objectinto the constructor to parse a DTD:
>>>f=StringIO("<!ELEMENT b EMPTY>")>>>dtd=etree.DTD(f)
Now you can use it to validate documents:
>>>root=etree.XML("<b/>")>>>print(dtd.validate(root))True>>>root=etree.XML("<b><a/></b>")>>>print(dtd.validate(root))False
The reason for the validation failure can be found in the error log:
>>>print(dtd.error_log.filter_from_errors()[0])<string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element b was declared EMPTY this one has content
As an alternative to parsing from a file, you can use theexternal_id keyword argument to parse from a catalog. Thefollowing example reads the DocBook DTD in version 4.2, if availablein the system catalog:
dtd=etree.DTD(external_id="-//OASIS//DTD DocBook XML V4.2//EN")
The DTD information is available as attributes on the DTD object. The methoditerelements provides an iterator over the element declarations:
>>>dtd=etree.DTD(StringIO('<!ELEMENT a EMPTY><!ELEMENT b EMPTY>'))>>>forelindtd.iterelements():...print(el.name)ab
The methodelements returns the element declarations as a list:
>>>dtd=etree.DTD(StringIO('<!ELEMENT a EMPTY><!ELEMENT b EMPTY>'))>>>len(dtd.elements())2
An element declaration object provides the following attributes/methods:
- name: The name of the element;
- type: The element type, one of "undefined", "empty", "any", "mixed", or "element";
- content: Element content declaration (see below);
- iterattributes(): Return an iterator over attribute declarations (see below);
- attributes(): Return a list of attribute declarations.
Thecontent attribute contains information about the content model of the element.These element content declaration objects form a binary tree (via theleft andrightattributes), that makes it possible to reconstruct the content model expression. Here's alist of all attributes:
- name: If this object represents an element in the content model expression,name is the name of the element, otherwise it isNone;
- type: The type of the node: one of "pcdata", "element", "seq", or "or";
- occur: How often this element (or this combination of elements) may occur:one of "once", "opt", "mult", or "plus"
- left: The left hand subexpression
- right: The right hand subexpression
For example, the element declaration<!ELEMENT a(a|b)+> resultsin the following element content declaration objects:
>>>dtd=etree.DTD(StringIO('<!ELEMENT a (a|b)+>'))>>>content=dtd.elements()[0].content>>>content.type,content.occur,content.name('or', 'plus', None)>>>left,right=content.left,content.right>>>left.type,left.occur,left.name('element', 'once', 'a')>>>right.type,right.occur,right.name('element', 'once', 'b')
Attributes declarations have the following attributes/methods:
- name: The name of the attribute;
- elemname: The name of the element the attribute belongs to;
- type: The attribute type, one of "cdata", "id", "idref", "idrefs", "entity","entities", "nmtoken", "nmtokens", "enumeration", or "notation";
- default: The type of the default value, one of "none", "required", "implied",or "fixed";
- defaultValue: The default value;
- itervalues(): Return an iterator over the allowed attribute values (if the attributeis of type "enumeration");
- values(): Return a list of allowed attribute values.
Entity declarations are available via theiterentities andentities methods:
>>> dtd = etree.DTD(StringIO('<!ENTITY hurz "@">'))>>> entity = dtd.entities()[0]>>> entity.name, entity.orig, entity.content('hurz', '@', '@')
TheRelaxNG class takes an ElementTree object to construct a Relax NGvalidator:
>>>f=StringIO('''\...<element name="a" xmlns="http://relaxng.org/ns/structure/1.0">... <zeroOrMore>... <element name="b">... <text />... </element>... </zeroOrMore>...</element>...''')>>>relaxng_doc=etree.parse(f)>>>relaxng=etree.RelaxNG(relaxng_doc)
Alternatively, pass a filename to thefile keyword argument to parse froma file. This also enables correct handling of include files from within theRelaxNG parser.
You can then validate some ElementTree document against the schema. You'll getback True if the document is valid against the Relax NG schema, and False ifnot:
>>>valid=StringIO('<a><b></b></a>')>>>doc=etree.parse(valid)>>>relaxng.validate(doc)True>>>invalid=StringIO('<a><c></c></a>')>>>doc2=etree.parse(invalid)>>>relaxng.validate(doc2)False
Calling the schema object has the same effect as calling its validatemethod. This is sometimes used in conditional statements:
>>>invalid=StringIO('<a><c></c></a>')>>>doc2=etree.parse(invalid)>>>ifnotrelaxng(doc2):...print("invalid!")invalid!
If you prefer getting an exception when validating, you can use theassert_ orassertValid methods:
>>>relaxng.assertValid(doc2)Traceback (most recent call last):...lxml.etree.DocumentInvalid:Did not expect element c there, line 1>>>relaxng.assert_(doc2)Traceback (most recent call last):...AssertionError:Did not expect element c there, line 1
If you want to find out why the validation failed in the second case, you canlook up the error log of the validation process and check it for relevantmessages:
>>>log=relaxng.error_log>>>print(log.last_error)<string>:1:0:ERROR:RELAXNGV:RELAXNG_ERR_ELEMWRONG: Did not expect element c there
You can see that the error (ERROR) happened during RelaxNG validation(RELAXNGV). The message then tells you what went wrong. You can alsolook at the error domain and its type directly:
>>>error=log.last_error>>>print(error.domain_name)RELAXNGV>>>print(error.type_name)RELAXNG_ERR_ELEMWRONG
Note that this error log is local to the RelaxNG object. It will onlycontain log entries that appeared during the validation.
Similar to XSLT, there's also a less efficient but easier shortcut method todo one-shot RelaxNG validation:
>>>doc.relaxng(relaxng_doc)True>>>doc2.relaxng(relaxng_doc)False
libxml2 does not currently support theRelaxNG Compact Syntax.However, ifrnc2rng is installed, lxml 3.6 and later can use itinternally to parse the input schema. It recognises the.rnc fileextension and also allows parsing an RNC schema from a string usingRelaxNG.from_rnc_string().
Alternatively, thetrang translator can convert the compact syntaxto the XML syntax, which can then be used with lxml.
lxml.etree also has XML Schema (XSD) support, using the classlxml.etree.XMLSchema. The API is very similar to the Relax NG and DTDclasses. Pass an ElementTree object to construct a XMLSchema validator:
>>>f=StringIO('''\...<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">...<xsd:element name="a" type="AType"/>...<xsd:complexType name="AType">... <xsd:sequence>... <xsd:element name="b" type="xsd:string" />... </xsd:sequence>...</xsd:complexType>...</xsd:schema>...''')>>>xmlschema_doc=etree.parse(f)>>>xmlschema=etree.XMLSchema(xmlschema_doc)
You can then validate some ElementTree document with this. Like with RelaxNG,you'll get back true if the document is valid against the XML schema, andfalse if not:
>>>valid=StringIO('<a><b></b></a>')>>>doc=etree.parse(valid)>>>xmlschema.validate(doc)True>>>invalid=StringIO('<a><c></c></a>')>>>doc2=etree.parse(invalid)>>>xmlschema.validate(doc2)False
Calling the schema object has the same effect as calling its validate method.This is sometimes used in conditional statements:
>>>invalid=StringIO('<a><c></c></a>')>>>doc2=etree.parse(invalid)>>>ifnotxmlschema(doc2):...print("invalid!")invalid!
If you prefer getting an exception when validating, you can use theassert_ orassertValid methods:
>>>xmlschema.assertValid(doc2)Traceback (most recent call last):...lxml.etree.DocumentInvalid:Element 'c': This element is not expected. Expected is ( b )., line 1>>>xmlschema.assert_(doc2)Traceback (most recent call last):...AssertionError:Element 'c': This element is not expected. Expected is ( b )., line 1
Error reporting works as for the RelaxNG class:
>>>log=xmlschema.error_log>>>error=log.last_error>>>print(error.domain_name)SCHEMASV>>>print(error.type_name)SCHEMAV_ELEMENT_CONTENT
If you were to print this log entry, you would get something like thefollowing. Note that the error message depends on the libxml2 version inuse:
<string>:1:ERROR::SCHEMAV_ELEMENT_CONTENT: Element 'c': This element is not expected. Expected is ( b ).
Similar to XSLT and RelaxNG, there's also a less efficient but easier shortcutmethod to do XML Schema validation:
>>>doc.xmlschema(xmlschema_doc)True>>>doc2.xmlschema(xmlschema_doc)False
From version 2.3 on lxml features ISO-Schematron support built on thede-facto reference implementation of Schematron, the pure-XSLT-1.0skeleton implementation. This is provided by the lxml.isoschematron packagethat implements the Schematron class, with an API compatible to the othervalidators'. Pass an Element or ElementTree object to construct a Schematronvalidator:
>>>fromlxmlimportisoschematron>>>f=StringIO('''\...<schema xmlns="http://purl.oclc.org/dsdl/schematron" >... <pattern>... <title>Sum equals 100%.</title>... <rule context="Total">... <assert test="sum(//Percent)=100">Sum is not 100%.</assert>... </rule>... </pattern>...</schema>...''')>>>sct_doc=etree.parse(f)>>>schematron=isoschematron.Schematron(sct_doc)
You can then validate some ElementTree document with this. Just like withXMLSchema or RelaxNG, you'll get back true if the document is valid against theschema, and false if not:
>>>valid=StringIO('''\...<Total>... <Percent>20</Percent>... <Percent>30</Percent>... <Percent>50</Percent>...</Total>...''')>>>doc=etree.parse(valid)>>>schematron.validate(doc)True>>>etree.SubElement(doc.getroot(),"Percent").text="10">>>schematron.validate(doc)False
Calling the schema object has the same effect as calling its validate method.This can be useful for conditional statements:
>>>is_valid=isoschematron.Schematron(sct_doc)>>>ifnotis_valid(doc):...print("invalid!")invalid!
Built on a pure-xslt implementation, the actual validator is created as anXSLT 1.0 stylesheet using these steps:
To allow more control over the individual steps, isoschematron.Schematronsupports an extended API:
Theinclude andexpand keyword arguments can be used to switch offsteps 1) and 2).
To set parameters for steps 1), 2) and 3) dictionaries containing parametersfor XSLT can be provided using the keyword argumentsinclude_params,expand_params orcompile_params. Schematron automatically converts theseparameters to stylesheet parameters so you need not worry to set stringparameters using quotes or to use XSLT.strparam(). If you ever need to pass anXPath as argument to the XSLT stylesheet you can pass in an etree.XPath object(see XPath and XSLT with lxml:Stylesheet-parameters for background on this).
Thephase parameter of the compile step is additionally exposed as a keywordargument. If set, it overrides occurrence incompile_params. Note thatisoschematron.Schematron might expose more common parameters as additional keywordargs in the future.
By settingstore_schematron to True, the (included-and-expanded) schematrondocument tree is stored and made available through theschematron property.
Similarly, settingstore_xslt to True will result in the validation XSLTdocument tree being kept; it can be retrieved through thevalidator_xsltproperty.
Finally, withstore_report set to True (default: False), the resultingvalidation report document gets stored and can be accessed as thevalidation_report property.
Using thephase parameter of isoschematron.Schematron allows for selectivevalidation of predefined pattern groups:
>>>f=StringIO('''\...<schema xmlns="http://purl.oclc.org/dsdl/schematron" >... <phase>... <active pattern="sum_equals_100_percent"/>... </phase>... <phase>... <active pattern="all_positive"/>... </phase>... <pattern>... <title>Sum equals 100%.</title>... <rule context="Total">... <assert test="sum(//Percent)=100">Sum is not 100%.</assert>... </rule>... </pattern>... <pattern>... <title>All entries must be positive.</title>... <rule context="Percent">... <assert test="number(.)>0">Number (<value-of select="."/>) not positive</assert>... </rule>... </pattern>...</schema>...''')>>>sct_doc=etree.parse(f)>>>schematron=isoschematron.Schematron(sct_doc)>>>valid=StringIO('''\...<Total>... <Percent>20</Percent>... <Percent>30</Percent>... <Percent>50</Percent>...</Total>...''')>>>doc=etree.parse(valid)>>>schematron.validate(doc)True>>>invalid_positive=StringIO('''\...<Total>... <Percent>0</Percent>... <Percent>50</Percent>... <Percent>50</Percent>...</Total>...''')>>>doc=etree.parse(invalid_positive)>>>schematron.validate(doc)False
If the constraint of Percent entries being positive is not of interest in acertain validation scenario, it can now be disabled:
>>>selective=isoschematron.Schematron(sct_doc,phase="phase.sum_check")>>>selective.validate(doc)True
The usage of validation phases is a unique feature of ISO-Schematron and can bea very powerful tool e.g. for establishing validation stages or to providedifferent validators for different "validation audiences".
Since version 2.0, lxml.etree featurespre-ISO-Schematron support, using theclass lxml.etree.Schematron. It requires at least libxml2 2.6.21 towork. The API is the same as for the other validators. Pass anElementTree object to construct a Schematron validator:
>>>f=StringIO('''\...<schema xmlns="http://www.ascc.net/xml/schematron" >... <pattern name="Sum equals 100%.">... <rule context="Total">... <assert test="sum(//Percent)=100">Sum is not 100%.</assert>... </rule>... </pattern>...</schema>...''')>>>sct_doc=etree.parse(f)>>>schematron=etree.Schematron(sct_doc)
You can then validate some ElementTree document with this. Like with RelaxNG,you'll get back true if the document is valid against the schema, and false ifnot:
>>>valid=StringIO('''\...<Total>... <Percent>20</Percent>... <Percent>30</Percent>... <Percent>50</Percent>...</Total>...''')>>>doc=etree.parse(valid)>>>schematron.validate(doc)True>>>etree.SubElement(doc.getroot(),"Percent").text="10">>>schematron.validate(doc)False
Calling the schema object has the same effect as calling its validate method.This is sometimes used in conditional statements:
>>>is_valid=etree.Schematron(sct_doc)>>>ifnotis_valid(doc):...print("invalid!")invalid!
Note that libxml2 restricts error reporting to the parsing step (when creatingthe Schematron instance). There is not currently any support for errorreporting during validation.