validation.txt 21 KB

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