XSLT and Validation in lxml

XSLT and Schema Validation in lxml

etree.XMLSchema, etree.RelaxNG and etree.XSLT compile once and run many times, as a feed checker needs. They are libxml2 3,427 's validators and libxslt 3,427 's XSLT 1.0, so the schemas of XSD 1.1 Types-RELAX NG and the stylesheet of XSLTProcessor in the Browser work unchanged:

validate.py: XSD 1.0 and RELAX NG verdicts, an XSLT 1.0 run, and XSD 1.1Python
from lxml import etree
doc = etree.parse("booknest-catalog.xml")
bad = etree.fromstring(etree.tostring(doc).replace(b">39.50<", b">-39.50<")).getroottree()
for name, validator in [("XSD 1.0", etree.XMLSchema(file="catalog.xsd")),
                        ("RELAX NG", etree.RelaxNG(file="booknest.rng"))]:
    ok, err = validator.validate(doc), validator.validate(bad)
    last = validator.error_log.last_error
    print(f"{name}: {ok}, {err}; line {last.line}: {last.message}")
shelf = etree.XSLT(etree.parse("shelf1.xsl"))          # XSLT 1.0 through libxslt
result = shelf(doc, min="30")                          # parameters are XPath expressions
print(str(result).strip())
try:
    etree.XMLSchema(file="catalog11.xsd")
except etree.XMLSchemaParseError as e:
    print("XSD 1.1:", str(e).split(". Expected")[0])
Output
XSD 1.0: True, False; line 40: Element 'price': [facet 'minExclusive'] The value '-39.50' must
  be greater than '0'.
RELAX NG: True, False; line 40: Element price failed to validate content
<?xml version="1.0"?>
<ul><li><b>Patterns of the Deep Web</b> $39.50</li></ul>
XSD 1.1: Element '{http://www.w3.org/2001/XMLSchema}schema': The content is not valid

error_log keeps each message with its line for a quarantine report. XSLT parameters are XPath expressions: pass strings as etree.XSLT.strparam("text"). The XSD 1.1 schema fails to compile, since libxml2 knows XSD 1.0 only (XSD 1.1 Types); for 1.1, and for XSLT 2.0 and later, use the tools below or Saxon 726,956 .