| 1 |
==================== |
| 2 |
Validation with lxml |
| 3 |
==================== |
| 4 |
|
| 5 |
Apart from the built-in DTD support in parsers, lxml currently supports three |
| 6 |
schema languages: DTD_, `Relax NG`_ and `XML Schema`_. All three provide |
| 7 |
identical APIs in lxml, represented by validator classes with the obvious |
| 8 |
names. |
| 9 |
|
| 10 |
.. _DTD: http://en.wikipedia.org/wiki/Document_Type_Definition |
| 11 |
.. _`Relax NG`: http://www.relaxng.org/ |
| 12 |
.. _`XML Schema`: http://www.w3.org/XML/Schema |
| 13 |
|
| 14 |
lxml also provides support for ISO-`Schematron`_, based on the pure-XSLT |
| 15 |
`skeleton implementation`_ of Schematron: |
| 16 |
|
| 17 |
.. _Schematron: http://www.schematron.com |
| 18 |
.. _`skeleton implementation`: http://www.schematron.com/implementation.html |
| 19 |
|
| 20 |
There is also basic support for `pre-ISO-Schematron`_ through the libxml2 |
| 21 |
Schematron features. However, this does not currently support error reporting |
| 22 |
in the validation phase due to insufficiencies in the implementation as of |
| 23 |
libxml2 2.6.30. |
| 24 |
|
| 25 |
.. _`pre-ISO-Schematron`: http://www.ascc.net/xml/schematron |
| 26 |
|
| 27 |
.. contents:: |
| 28 |
.. |
| 29 |
1 Validation at parse time |
| 30 |
2 DTD |
| 31 |
3 RelaxNG |
| 32 |
4 XMLSchema |
| 33 |
5 Schematron |
| 34 |
6 (Pre-ISO-Schematron) |
| 35 |
|
| 36 |
The usual setup procedure: |
| 37 |
|
| 38 |
.. sourcecode:: pycon |
| 39 |
|
| 40 |
>>> from lxml import etree |
| 41 |
|
| 42 |
.. |
| 43 |
>>> try: from StringIO import StringIO |
| 44 |
... except ImportError: |
| 45 |
... from io import BytesIO |
| 46 |
... def StringIO(s): |
| 47 |
... if isinstance(s, str): s = s.encode("UTF-8") |
| 48 |
... return BytesIO(s) |
| 49 |
|
| 50 |
|
| 51 |
Validation at parse time |
| 52 |
------------------------ |
| 53 |
|
| 54 |
The parser in lxml can do on-the-fly validation of a document against |
| 55 |
a DTD or an XML schema. The DTD is retrieved automatically based on |
| 56 |
the DOCTYPE of the parsed document. All you have to do is use a |
| 57 |
parser that has DTD validation enabled: |
| 58 |
|
| 59 |
.. sourcecode:: pycon |
| 60 |
|
| 61 |
>>> parser = etree.XMLParser(dtd_validation=True) |
| 62 |
|
| 63 |
Obviously, a request for validation enables the DTD loading feature. |
| 64 |
There are two other options that enable loading the DTD, but that do |
| 65 |
not perform any validation. The first is the ``load_dtd`` keyword |
| 66 |
option, which simply loads the DTD into the parser and makes it |
| 67 |
available to the document as external subset. You can retrieve the |
| 68 |
DTD from the parsed document using the ``docinfo`` property of the |
| 69 |
result ElementTree object. The internal subset is available as |
| 70 |
``internalDTD``, the external subset is provided as ``externalDTD``. |
| 71 |
|
| 72 |
The third way to activate DTD loading is with the |
| 73 |
``attribute_defaults`` option, which loads the DTD and weaves |
| 74 |
attribute default values into the document. Again, no validation is |
| 75 |
performed unless explicitly requested. |
| 76 |
|
| 77 |
XML schema is supported in a similar way, but requires an explicit |
| 78 |
schema to be provided: |
| 79 |
|
| 80 |
.. sourcecode:: pycon |
| 81 |
|
| 82 |
>>> schema_root = etree.XML('''\ |
| 83 |
... <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> |
| 84 |
... <xsd:element name="a" type="xsd:integer"/> |
| 85 |
... </xsd:schema> |
| 86 |
... ''') |
| 87 |
>>> schema = etree.XMLSchema(schema_root) |
| 88 |
|
| 89 |
>>> parser = etree.XMLParser(schema = schema) |
| 90 |
>>> root = etree.fromstring("<a>5</a>", parser) |
| 91 |
|
| 92 |
If the validation fails (be it for a DTD or an XML schema), the parser |
| 93 |
will raise an exception: |
| 94 |
|
| 95 |
.. sourcecode:: pycon |
| 96 |
|
| 97 |
>>> root = etree.fromstring("<a>no int</a>", parser) # doctest: +ELLIPSIS |
| 98 |
Traceback (most recent call last): |
| 99 |
lxml.etree.XMLSyntaxError: Element 'a': 'no int' is not a valid value of the atomic type 'xs:integer'... |
| 100 |
|
| 101 |
If you want the parser to succeed regardless of the outcome of the |
| 102 |
validation, you should use a non validating parser and run the |
| 103 |
validation separately after parsing the document. |
| 104 |
|
| 105 |
|
| 106 |
DTD |
| 107 |
--- |
| 108 |
|
| 109 |
As described above, the parser support for DTDs depends on internal or |
| 110 |
external subsets of the XML file. This means that the XML file itself |
| 111 |
must either contain a DTD or must reference a DTD to make this work. |
| 112 |
If you want to validate an XML document against a DTD that is not |
| 113 |
referenced by the document itself, you can use the ``DTD`` class. |
| 114 |
|
| 115 |
To use the ``DTD`` class, you must first pass a filename or file-like object |
| 116 |
into the constructor to parse a DTD: |
| 117 |
|
| 118 |
.. sourcecode:: pycon |
| 119 |
|
| 120 |
>>> f = StringIO("<!ELEMENT b EMPTY>") |
| 121 |
>>> dtd = etree.DTD(f) |
| 122 |
|
| 123 |
Now you can use it to validate documents: |
| 124 |
|
| 125 |
.. sourcecode:: pycon |
| 126 |
|
| 127 |
>>> root = etree.XML("<b/>") |
| 128 |
>>> print(dtd.validate(root)) |
| 129 |
True |
| 130 |
|
| 131 |
>>> root = etree.XML("<b><a/></b>") |
| 132 |
>>> print(dtd.validate(root)) |
| 133 |
False |
| 134 |
|
| 135 |
The reason for the validation failure can be found in the error log: |
| 136 |
|
| 137 |
.. sourcecode:: pycon |
| 138 |
|
| 139 |
>>> print(dtd.error_log.filter_from_errors()[0]) |
| 140 |
<string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element b was declared EMPTY this one has content |
| 141 |
|
| 142 |
As an alternative to parsing from a file, you can use the |
| 143 |
``external_id`` keyword argument to parse from a catalog. The |
| 144 |
following example reads the DocBook DTD in version 4.2, if available |
| 145 |
in the system catalog: |
| 146 |
|
| 147 |
.. sourcecode:: python |
| 148 |
|
| 149 |
dtd = etree.DTD(external_id = "-//OASIS//DTD DocBook XML V4.2//EN") |
| 150 |
|
| 151 |
The DTD information is available as attributes on the DTD object. The method |
| 152 |
``iterelements`` provides an iterator over the element declarations: |
| 153 |
|
| 154 |
.. sourcecode:: pycon |
| 155 |
|
| 156 |
>>> dtd = etree.DTD(StringIO('<!ELEMENT a EMPTY><!ELEMENT b EMPTY>')) |
| 157 |
>>> for el in dtd.iterelements(): |
| 158 |
... print(el.name) |
| 159 |
a |
| 160 |
b |
| 161 |
|
| 162 |
The method ``elements`` returns the element declarations as a list: |
| 163 |
|
| 164 |
.. sourcecode:: pycon |
| 165 |
|
| 166 |
>>> dtd = etree.DTD(StringIO('<!ELEMENT a EMPTY><!ELEMENT b EMPTY>')) |
| 167 |
>>> len(dtd.elements()) |
| 168 |
2 |
| 169 |
|
| 170 |
An element declaration object provides the following attributes/methods: |
| 171 |
|
| 172 |
- ``name``: The name of the element; |
| 173 |
|
| 174 |
- ``type``: The element type, one of "undefined", "empty", "any", "mixed", or "element"; |
| 175 |
|
| 176 |
- ``content``: Element content declaration (see below); |
| 177 |
|
| 178 |
- ``iterattributes()``: Return an iterator over attribute declarations (see below); |
| 179 |
|
| 180 |
- ``attributes()``: Return a list of attribute declarations. |
| 181 |
|
| 182 |
The ``content`` attribute contains information about the content model of the element. |
| 183 |
These element content declaration objects form a binary tree (via the ``left`` and ``right`` |
| 184 |
attributes), that makes it possible to reconstruct the content model expression. Here's a |
| 185 |
list of all attributes: |
| 186 |
|
| 187 |
- ``name``: If this object represents an element in the content model expression, |
| 188 |
``name`` is the name of the element, otherwise it is ``None``; |
| 189 |
|
| 190 |
- ``type``: The type of the node: one of "pcdata", "element", "seq", or "or"; |
| 191 |
|
| 192 |
- ``occur``: How often this element (or this combination of elements) may occur: |
| 193 |
one of "once", "opt", "mult", or "plus" |
| 194 |
|
| 195 |
- ``left``: The left hand subexpression |
| 196 |
|
| 197 |
- ``right``: The right hand subexpression |
| 198 |
|
| 199 |
For example, the element declaration ``<!ELEMENT a (a|b)+>`` results |
| 200 |
in the following element content declaration objects: |
| 201 |
|
| 202 |
.. sourcecode:: pycon |
| 203 |
|
| 204 |
>>> dtd = etree.DTD(StringIO('<!ELEMENT a (a|b)+>')) |
| 205 |
>>> content = dtd.elements()[0].content |
| 206 |
>>> content.type, content.occur, content.name |
| 207 |
('or', 'plus', None) |
| 208 |
|
| 209 |
>>> left, right = content.left, content.right |
| 210 |
>>> left.type, left.occur, left.name |
| 211 |
('element', 'once', 'a') |
| 212 |
>>> right.type, right.occur, right.name |
| 213 |
('element', 'once', 'b') |
| 214 |
|
| 215 |
Attributes declarations have the following attributes/methods: |
| 216 |
|
| 217 |
- ``name``: The name of the attribute; |
| 218 |
|
| 219 |
- ``elemname``: The name of the element the attribute belongs to; |
| 220 |
|
| 221 |
- ``type``: The attribute type, one of "cdata", "id", "idref", "idrefs", "entity", |
| 222 |
"entities", "nmtoken", "nmtokens", "enumeration", or "notation"; |
| 223 |
|
| 224 |
- ``default``: The type of the default value, one of "none", "required", "implied", |
| 225 |
or "fixed"; |
| 226 |
|
| 227 |
- ``defaultValue``: The default value; |
| 228 |
|
| 229 |
- ``itervalues()``: Return an iterator over the allowed attribute values (if the attribute |
| 230 |
is of type "enumeration"); |
| 231 |
|
| 232 |
- ``values()``: Return a list of allowed attribute values. |
| 233 |
|
| 234 |
Entity declarations are available via the ``iterentities`` and ``entities`` methods: |
| 235 |
|
| 236 |
>>> dtd = etree.DTD(StringIO('<!ENTITY hurz "@">')) |
| 237 |
>>> entity = dtd.entities()[0] |
| 238 |
>>> entity.name, entity.orig, entity.content |
| 239 |
('hurz', '@', '@') |
| 240 |
|
| 241 |
|
| 242 |
RelaxNG |
| 243 |
------- |
| 244 |
|
| 245 |
The ``RelaxNG`` class takes an ElementTree object to construct a Relax NG |
| 246 |
validator: |
| 247 |
|
| 248 |
.. sourcecode:: pycon |
| 249 |
|
| 250 |
>>> f = StringIO('''\ |
| 251 |
... <element name="a" xmlns="http://relaxng.org/ns/structure/1.0"> |
| 252 |
... <zeroOrMore> |
| 253 |
... <element name="b"> |
| 254 |
... <text /> |
| 255 |
... </element> |
| 256 |
... </zeroOrMore> |
| 257 |
... </element> |
| 258 |
... ''') |
| 259 |
>>> relaxng_doc = etree.parse(f) |
| 260 |
>>> relaxng = etree.RelaxNG(relaxng_doc) |
| 261 |
|
| 262 |
Alternatively, pass a filename to the ``file`` keyword argument to parse from |
| 263 |
a file. This also enables correct handling of include files from within the |
| 264 |
RelaxNG parser. |
| 265 |
|
| 266 |
You can then validate some ElementTree document against the schema. You'll get |
| 267 |
back True if the document is valid against the Relax NG schema, and False if |
| 268 |
not: |
| 269 |
|
| 270 |
.. sourcecode:: pycon |
| 271 |
|
| 272 |
>>> valid = StringIO('<a><b></b></a>') |
| 273 |
>>> doc = etree.parse(valid) |
| 274 |
>>> relaxng.validate(doc) |
| 275 |
True |
| 276 |
|
| 277 |
>>> invalid = StringIO('<a><c></c></a>') |
| 278 |
>>> doc2 = etree.parse(invalid) |
| 279 |
>>> relaxng.validate(doc2) |
| 280 |
False |
| 281 |
|
| 282 |
Calling the schema object has the same effect as calling its validate |
| 283 |
method. This is sometimes used in conditional statements: |
| 284 |
|
| 285 |
.. sourcecode:: pycon |
| 286 |
|
| 287 |
>>> invalid = StringIO('<a><c></c></a>') |
| 288 |
>>> doc2 = etree.parse(invalid) |
| 289 |
>>> if not relaxng(doc2): |
| 290 |
... print("invalid!") |
| 291 |
invalid! |
| 292 |
|
| 293 |
If you prefer getting an exception when validating, you can use the |
| 294 |
``assert_`` or ``assertValid`` methods: |
| 295 |
|
| 296 |
.. sourcecode:: pycon |
| 297 |
|
| 298 |
>>> relaxng.assertValid(doc2) |
| 299 |
Traceback (most recent call last): |
| 300 |
... |
| 301 |
lxml.etree.DocumentInvalid: Did not expect element c there, line 1 |
| 302 |
|
| 303 |
>>> relaxng.assert_(doc2) |
| 304 |
Traceback (most recent call last): |
| 305 |
... |
| 306 |
AssertionError: Did not expect element c there, line 1 |
| 307 |
|
| 308 |
If you want to find out why the validation failed in the second case, you can |
| 309 |
look up the error log of the validation process and check it for relevant |
| 310 |
messages: |
| 311 |
|
| 312 |
.. sourcecode:: pycon |
| 313 |
|
| 314 |
>>> log = relaxng.error_log |
| 315 |
>>> print(log.last_error) |
| 316 |
<string>:1:0:ERROR:RELAXNGV:RELAXNG_ERR_ELEMWRONG: Did not expect element c there |
| 317 |
|
| 318 |
You can see that the error (ERROR) happened during RelaxNG validation |
| 319 |
(RELAXNGV). The message then tells you what went wrong. You can also |
| 320 |
look at the error domain and its type directly: |
| 321 |
|
| 322 |
.. sourcecode:: pycon |
| 323 |
|
| 324 |
>>> error = log.last_error |
| 325 |
>>> print(error.domain_name) |
| 326 |
RELAXNGV |
| 327 |
>>> print(error.type_name) |
| 328 |
RELAXNG_ERR_ELEMWRONG |
| 329 |
|
| 330 |
Note that this error log is local to the RelaxNG object. It will only |
| 331 |
contain log entries that appeared during the validation. |
| 332 |
|
| 333 |
Similar to XSLT, there's also a less efficient but easier shortcut method to |
| 334 |
do one-shot RelaxNG validation: |
| 335 |
|
| 336 |
.. sourcecode:: pycon |
| 337 |
|
| 338 |
>>> doc.relaxng(relaxng_doc) |
| 339 |
True |
| 340 |
>>> doc2.relaxng(relaxng_doc) |
| 341 |
False |
| 342 |
|
| 343 |
libxml2 does not currently support the `RelaxNG Compact Syntax`_. |
| 344 |
However, if `rnc2rng`_ is installed, lxml 3.6 and later can use it |
| 345 |
internally to parse the input schema. It recognises the `.rnc` file |
| 346 |
extension and also allows parsing an RNC schema from a string using |
| 347 |
`RelaxNG.from_rnc_string()`. |
| 348 |
|
| 349 |
Alternatively, the trang_ translator can convert the compact syntax |
| 350 |
to the XML syntax, which can then be used with lxml. |
| 351 |
|
| 352 |
.. _`rnc2rng`: https://pypi.python.org/pypi/rnc2rng |
| 353 |
.. _`RelaxNG Compact Syntax`: http://relaxng.org/compact-tutorial.html |
| 354 |
.. _trang: http://www.thaiopensource.com/relaxng/trang.html |
| 355 |
|
| 356 |
|
| 357 |
XMLSchema |
| 358 |
--------- |
| 359 |
|
| 360 |
lxml.etree also has XML Schema (XSD) support, using the class |
| 361 |
lxml.etree.XMLSchema. The API is very similar to the Relax NG and DTD |
| 362 |
classes. Pass an ElementTree object to construct an XMLSchema validator: |
| 363 |
|
| 364 |
.. sourcecode:: pycon |
| 365 |
|
| 366 |
>>> f = StringIO('''\ |
| 367 |
... <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> |
| 368 |
... <xsd:element name="a" type="AType"/> |
| 369 |
... <xsd:complexType name="AType"> |
| 370 |
... <xsd:sequence> |
| 371 |
... <xsd:element name="b" type="xsd:string" /> |
| 372 |
... </xsd:sequence> |
| 373 |
... </xsd:complexType> |
| 374 |
... </xsd:schema> |
| 375 |
... ''') |
| 376 |
>>> xmlschema_doc = etree.parse(f) |
| 377 |
>>> xmlschema = etree.XMLSchema(xmlschema_doc) |
| 378 |
|
| 379 |
You can then validate some ElementTree document with this. Like with RelaxNG, |
| 380 |
you'll get back True if the document is valid against the XML schema, and |
| 381 |
False if not: |
| 382 |
|
| 383 |
.. sourcecode:: pycon |
| 384 |
|
| 385 |
>>> valid = StringIO('<a><b></b></a>') |
| 386 |
>>> doc = etree.parse(valid) |
| 387 |
>>> xmlschema.validate(doc) |
| 388 |
True |
| 389 |
|
| 390 |
>>> invalid = StringIO('<a><c></c></a>') |
| 391 |
>>> doc2 = etree.parse(invalid) |
| 392 |
>>> xmlschema.validate(doc2) |
| 393 |
False |
| 394 |
|
| 395 |
Calling the schema object has the same effect as calling its validate method. |
| 396 |
This is sometimes used in conditional statements: |
| 397 |
|
| 398 |
.. sourcecode:: pycon |
| 399 |
|
| 400 |
>>> invalid = StringIO('<a><c></c></a>') |
| 401 |
>>> doc2 = etree.parse(invalid) |
| 402 |
>>> if not xmlschema(doc2): |
| 403 |
... print("invalid!") |
| 404 |
invalid! |
| 405 |
|
| 406 |
If you prefer getting an exception when validating, you can use the |
| 407 |
``assert_`` or ``assertValid`` methods: |
| 408 |
|
| 409 |
.. sourcecode:: pycon |
| 410 |
|
| 411 |
>>> xmlschema.assertValid(doc2) |
| 412 |
Traceback (most recent call last): |
| 413 |
... |
| 414 |
lxml.etree.DocumentInvalid: Element 'c': This element is not expected. Expected is ( b )., line 1 |
| 415 |
|
| 416 |
>>> xmlschema.assert_(doc2) |
| 417 |
Traceback (most recent call last): |
| 418 |
... |
| 419 |
AssertionError: Element 'c': This element is not expected. Expected is ( b )., line 1 |
| 420 |
|
| 421 |
Error reporting works as for the RelaxNG class: |
| 422 |
|
| 423 |
.. sourcecode:: pycon |
| 424 |
|
| 425 |
>>> log = xmlschema.error_log |
| 426 |
>>> error = log.last_error |
| 427 |
>>> print(error.domain_name) |
| 428 |
SCHEMASV |
| 429 |
>>> print(error.type_name) |
| 430 |
SCHEMAV_ELEMENT_CONTENT |
| 431 |
|
| 432 |
If you were to print this log entry, you would get something like the |
| 433 |
following. Note that the error message depends on the libxml2 version in |
| 434 |
use:: |
| 435 |
|
| 436 |
<string>:1:ERROR::SCHEMAV_ELEMENT_CONTENT: Element 'c': This element is not expected. Expected is ( b ). |
| 437 |
|
| 438 |
Similar to XSLT and RelaxNG, there's also a less efficient but easier shortcut |
| 439 |
method to do XML Schema validation: |
| 440 |
|
| 441 |
.. sourcecode:: pycon |
| 442 |
|
| 443 |
>>> doc.xmlschema(xmlschema_doc) |
| 444 |
True |
| 445 |
>>> doc2.xmlschema(xmlschema_doc) |
| 446 |
False |
| 447 |
|
| 448 |
Schematron |
| 449 |
---------- |
| 450 |
|
| 451 |
From version 2.3 on lxml features ISO-`Schematron`_ support built on the |
| 452 |
de-facto reference implementation of Schematron, the pure-XSLT-1.0 |
| 453 |
`skeleton implementation`_. This is provided by the lxml.isoschematron package |
| 454 |
that implements the Schematron class, with an API compatible to the other |
| 455 |
validators'. Pass an Element or ElementTree object to construct a Schematron |
| 456 |
validator: |
| 457 |
|
| 458 |
.. sourcecode:: pycon |
| 459 |
|
| 460 |
>>> from lxml import isoschematron |
| 461 |
>>> f = StringIO('''\ |
| 462 |
... <schema xmlns="http://purl.oclc.org/dsdl/schematron" > |
| 463 |
... <pattern id="sum_equals_100_percent"> |
| 464 |
... <title>Sum equals 100%.</title> |
| 465 |
... <rule context="Total"> |
| 466 |
... <assert test="sum(//Percent)=100">Sum is not 100%.</assert> |
| 467 |
... </rule> |
| 468 |
... </pattern> |
| 469 |
... </schema> |
| 470 |
... ''') |
| 471 |
|
| 472 |
>>> sct_doc = etree.parse(f) |
| 473 |
>>> schematron = isoschematron.Schematron(sct_doc) |
| 474 |
|
| 475 |
You can then validate some ElementTree document with this. Just like with |
| 476 |
XMLSchema or RelaxNG, you'll get back true if the document is valid against the |
| 477 |
schema, and false if not: |
| 478 |
|
| 479 |
.. sourcecode:: pycon |
| 480 |
|
| 481 |
>>> valid = StringIO('''\ |
| 482 |
... <Total> |
| 483 |
... <Percent>20</Percent> |
| 484 |
... <Percent>30</Percent> |
| 485 |
... <Percent>50</Percent> |
| 486 |
... </Total> |
| 487 |
... ''') |
| 488 |
|
| 489 |
>>> doc = etree.parse(valid) |
| 490 |
>>> schematron.validate(doc) |
| 491 |
True |
| 492 |
|
| 493 |
>>> etree.SubElement(doc.getroot(), "Percent").text = "10" |
| 494 |
|
| 495 |
>>> schematron.validate(doc) |
| 496 |
False |
| 497 |
|
| 498 |
Calling the schema object has the same effect as calling its validate method. |
| 499 |
This can be useful for conditional statements: |
| 500 |
|
| 501 |
.. sourcecode:: pycon |
| 502 |
|
| 503 |
>>> is_valid = isoschematron.Schematron(sct_doc) |
| 504 |
|
| 505 |
>>> if not is_valid(doc): |
| 506 |
... print("invalid!") |
| 507 |
invalid! |
| 508 |
|
| 509 |
Built on a pure-xslt implementation, the actual validator is created as an |
| 510 |
XSLT 1.0 stylesheet using these steps: |
| 511 |
|
| 512 |
0. (Extract embedded Schematron from XML Schema or RelaxNG schema) |
| 513 |
1. Process inclusions |
| 514 |
2. Process abstract patterns |
| 515 |
3. Compile the schematron schema to XSLT |
| 516 |
|
| 517 |
To allow more control over the individual steps, isoschematron.Schematron |
| 518 |
supports an extended API: |
| 519 |
|
| 520 |
The ``include`` and ``expand`` keyword arguments can be used to switch off |
| 521 |
steps 1) and 2). |
| 522 |
|
| 523 |
To set parameters for steps 1), 2) and 3) dictionaries containing parameters |
| 524 |
for XSLT can be provided using the keyword arguments ``include_params``, |
| 525 |
``expand_params`` or ``compile_params``. Schematron automatically converts these |
| 526 |
parameters to stylesheet parameters so you need not worry about setting string |
| 527 |
parameters using quotes or to use XSLT.strparam(). If you ever need to pass an |
| 528 |
XPath as argument to the XSLT stylesheet you can pass in an etree.XPath object |
| 529 |
(see XPath and XSLT with lxml: Stylesheet-parameters_ for background on this). |
| 530 |
|
| 531 |
The ``phase`` parameter of the compile step is additionally exposed as a keyword |
| 532 |
argument. If set, it overrides occurrence in ``compile_params``. Note that |
| 533 |
isoschematron.Schematron might expose more common parameters as additional keyword |
| 534 |
args in the future. |
| 535 |
|
| 536 |
By setting ``store_schematron`` to True, the (included-and-expanded) schematron |
| 537 |
document tree is stored and made available through the ``schematron`` property. |
| 538 |
|
| 539 |
Similarly, setting ``store_xslt`` to True will result in the validation XSLT |
| 540 |
document tree being kept; it can be retrieved through the ``validator_xslt`` |
| 541 |
property. |
| 542 |
|
| 543 |
Finally, with ``store_report`` set to True (default: False), the resulting |
| 544 |
validation report document gets stored and can be accessed as the |
| 545 |
``validation_report`` property. |
| 546 |
|
| 547 |
.. _Stylesheet-parameters: xpathxslt.html#stylesheet-parameters |
| 548 |
|
| 549 |
Using the ``phase`` parameter of isoschematron.Schematron allows for selective |
| 550 |
validation of predefined pattern groups: |
| 551 |
|
| 552 |
.. sourcecode:: pycon |
| 553 |
|
| 554 |
>>> f = StringIO('''\ |
| 555 |
... <schema xmlns="http://purl.oclc.org/dsdl/schematron" > |
| 556 |
... <phase id="phase.sum_check"> |
| 557 |
... <active pattern="sum_equals_100_percent"/> |
| 558 |
... </phase> |
| 559 |
... <phase id="phase.entries_check"> |
| 560 |
... <active pattern="all_positive"/> |
| 561 |
... </phase> |
| 562 |
... <pattern id="sum_equals_100_percent"> |
| 563 |
... <title>Sum equals 100%.</title> |
| 564 |
... <rule context="Total"> |
| 565 |
... <assert test="sum(//Percent)=100">Sum is not 100%.</assert> |
| 566 |
... </rule> |
| 567 |
... </pattern> |
| 568 |
... <pattern id="all_positive"> |
| 569 |
... <title>All entries must be positive.</title> |
| 570 |
... <rule context="Percent"> |
| 571 |
... <assert test="number(.)>0">Number (<value-of select="."/>) not positive</assert> |
| 572 |
... </rule> |
| 573 |
... </pattern> |
| 574 |
... </schema> |
| 575 |
... ''') |
| 576 |
|
| 577 |
>>> sct_doc = etree.parse(f) |
| 578 |
>>> schematron = isoschematron.Schematron(sct_doc) |
| 579 |
|
| 580 |
>>> valid = StringIO('''\ |
| 581 |
... <Total> |
| 582 |
... <Percent>20</Percent> |
| 583 |
... <Percent>30</Percent> |
| 584 |
... <Percent>50</Percent> |
| 585 |
... </Total> |
| 586 |
... ''') |
| 587 |
|
| 588 |
>>> doc = etree.parse(valid) |
| 589 |
>>> schematron.validate(doc) |
| 590 |
True |
| 591 |
|
| 592 |
>>> invalid_positive = StringIO('''\ |
| 593 |
... <Total> |
| 594 |
... <Percent>0</Percent> |
| 595 |
... <Percent>50</Percent> |
| 596 |
... <Percent>50</Percent> |
| 597 |
... </Total> |
| 598 |
... ''') |
| 599 |
|
| 600 |
>>> doc = etree.parse(invalid_positive) |
| 601 |
|
| 602 |
>>> schematron.validate(doc) |
| 603 |
False |
| 604 |
|
| 605 |
If the constraint of Percent entries being positive is not of interest in a |
| 606 |
certain validation scenario, it can now be disabled: |
| 607 |
|
| 608 |
.. sourcecode:: pycon |
| 609 |
|
| 610 |
>>> selective = isoschematron.Schematron(sct_doc, phase="phase.sum_check") |
| 611 |
>>> selective.validate(doc) |
| 612 |
True |
| 613 |
|
| 614 |
The usage of validation phases is a unique feature of ISO-Schematron and can be |
| 615 |
a very powerful tool e.g. for establishing validation stages or to provide |
| 616 |
different validators for different "validation audiences". |
| 617 |
|
| 618 |
Note: Some lxml distributions exclude the validation schema file due to licensing issues. |
| 619 |
Since lxml 5.0, the validation of the user provided schema can be disabled with |
| 620 |
``Schematron(..., validate_schema=False)``. |
| 621 |
It is enabled by default if available and disabled otherwise. Previous versions of |
| 622 |
lxml always had it enabled and failed at import time if the file was not available. |
| 623 |
Thus, some distributions chose to remove the entire ISO-Schematron support. |
| 624 |
The module constant ``lxml.isoschematron.schematron_schema_valid_supported`` can be used |
| 625 |
since lxml 5.0 to detect whether schema file validation is available. |
| 626 |
|
| 627 |
(Pre-ISO-Schematron) |
| 628 |
-------------------- |
| 629 |
|
| 630 |
In libxml2 versions that provide it, lxml.etree features `pre-ISO-Schematron`_ support, |
| 631 |
using the class lxml.etree.Schematron. It requires at least libxml2 2.6.21 to |
| 632 |
work but is no longer available in libxml2 2.15. To test if lxml provides this, |
| 633 |
use ``"schematron" in etree.LIBXML_FEATURES``. |
| 634 |
|
| 635 |
The API is the same as for the other validators. |
| 636 |
Pass an ElementTree object to construct a Schematron validator:: |
| 637 |
|
| 638 |
f = StringIO('''\ |
| 639 |
<schema xmlns="http://www.ascc.net/xml/schematron" > |
| 640 |
<pattern name="Sum equals 100%."> |
| 641 |
<rule context="Total"> |
| 642 |
<assert test="sum(//Percent)=100">Sum is not 100%.</assert> |
| 643 |
</rule> |
| 644 |
</pattern> |
| 645 |
</schema> |
| 646 |
''') |
| 647 |
|
| 648 |
sct_doc = etree.parse(f) |
| 649 |
schematron = etree.Schematron(sct_doc) |
| 650 |
|
| 651 |
You can then validate some ElementTree document with this. Like with RelaxNG, |
| 652 |
you'll get back true if the document is valid against the schema, and false if |
| 653 |
not:: |
| 654 |
|
| 655 |
valid = StringIO('''\ |
| 656 |
<Total> |
| 657 |
<Percent>20</Percent> |
| 658 |
<Percent>30</Percent> |
| 659 |
<Percent>50</Percent> |
| 660 |
</Total> |
| 661 |
''') |
| 662 |
|
| 663 |
doc = etree.parse(valid) |
| 664 |
assert schematron.validate(doc) |
| 665 |
|
| 666 |
etree.SubElement(doc.getroot(), "Percent").text = "10" |
| 667 |
assert not schematron.validate(doc) |
| 668 |
|
| 669 |
Calling the schema object has the same effect as calling its validate method. |
| 670 |
This is sometimes used in conditional statements:: |
| 671 |
|
| 672 |
is_valid = etree.Schematron(sct_doc) |
| 673 |
|
| 674 |
if not is_valid(doc): |
| 675 |
print("invalid!") |
| 676 |
|
| 677 |
Note that libxml2 restricts error reporting to the parsing step (when creating |
| 678 |
the Schematron instance). There is not currently any support for error |
| 679 |
reporting during validation. |