validation.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. There is also initial support for Schematron_. However, it does not currently
  12. support error reporting in the validation phase due to insufficiencies in the
  13. implementation as of libxml2 2.6.30.
  14. .. _Schematron: http://www.ascc.net/xml/schematron
  15. .. contents::
  16. ..
  17. 1 Validation at parse time
  18. 2 DTD
  19. 3 RelaxNG
  20. 4 XMLSchema
  21. 5 Schematron
  22. The usual setup procedure:
  23. .. sourcecode:: pycon
  24. >>> from lxml import etree
  25. ..
  26. >>> try: from StringIO import StringIO
  27. ... except ImportError:
  28. ... from io import BytesIO
  29. ... def StringIO(s):
  30. ... if isinstance(s, str): s = s.encode("UTF-8")
  31. ... return BytesIO(s)
  32. Validation at parse time
  33. ------------------------
  34. The parser in lxml can do on-the-fly validation of a document against
  35. a DTD or an XML schema. The DTD is retrieved automatically based on
  36. the DOCTYPE of the parsed document. All you have to do is use a
  37. parser that has DTD validation enabled:
  38. .. sourcecode:: pycon
  39. >>> parser = etree.XMLParser(dtd_validation=True)
  40. Obviously, a request for validation enables the DTD loading feature.
  41. There are two other options that enable loading the DTD, but that do
  42. not perform any validation. The first is the ``load_dtd`` keyword
  43. option, which simply loads the DTD into the parser and makes it
  44. available to the document as external subset. You can retrieve the
  45. DTD from the parsed document using the ``docinfo`` property of the
  46. result ElementTree object. The internal subset is available as
  47. ``internalDTD``, the external subset is provided as ``externalDTD``.
  48. The third way way to activate DTD loading is with the
  49. ``attribute_defaults`` option, which loads the DTD and weaves
  50. attribute default values into the document. Again, no validation is
  51. performed unless explicitly requested.
  52. XML schema is supported in a similar way, but requires an explicit
  53. schema to be provided:
  54. .. sourcecode:: pycon
  55. >>> schema_root = etree.XML('''\
  56. ... <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  57. ... <xsd:element name="a" type="xsd:integer"/>
  58. ... </xsd:schema>
  59. ... ''')
  60. >>> schema = etree.XMLSchema(schema_root)
  61. >>> parser = etree.XMLParser(schema = schema)
  62. >>> root = etree.fromstring("<a>5</a>", parser)
  63. If the validation fails (be it for a DTD or an XML schema), the parser
  64. will raise an exception:
  65. .. sourcecode:: pycon
  66. >>> root = etree.fromstring("<a>no int</a>", parser)
  67. Traceback (most recent call last):
  68. lxml.etree.XMLSyntaxError: Element 'a': 'no int' is not a valid value of the atomic type 'xs:integer'.
  69. If you want the parser to succeed regardless of the outcome of the
  70. validation, you should use a non validating parser and run the
  71. validation separately after parsing the document.
  72. DTD
  73. ---
  74. As described above, the parser support for DTDs depends on internal or
  75. external subsets of the XML file. This means that the XML file itself
  76. must either contain a DTD or must reference a DTD to make this work.
  77. If you want to validate an XML document against a DTD that is not
  78. referenced by the document itself, you can use the ``DTD`` class.
  79. To use the ``DTD`` class, you must first pass a filename or file-like object
  80. into the constructor to parse a DTD:
  81. .. sourcecode:: pycon
  82. >>> f = StringIO("<!ELEMENT b EMPTY>")
  83. >>> dtd = etree.DTD(f)
  84. Now you can use it to validate documents:
  85. .. sourcecode:: pycon
  86. >>> root = etree.XML("<b/>")
  87. >>> print(dtd.validate(root))
  88. True
  89. >>> root = etree.XML("<b><a/></b>")
  90. >>> print(dtd.validate(root))
  91. False
  92. The reason for the validation failure can be found in the error log:
  93. .. sourcecode:: pycon
  94. >>> print(dtd.error_log.filter_from_errors()[0])
  95. <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element b was declared EMPTY this one has content
  96. As an alternative to parsing from a file, you can use the
  97. ``external_id`` keyword argument to parse from a catalog. The
  98. following example reads the DocBook DTD in version 4.2, if available
  99. in the system catalog:
  100. .. sourcecode:: python
  101. dtd = etree.DTD(external_id = "-//OASIS//DTD DocBook XML V4.2//EN")
  102. RelaxNG
  103. -------
  104. The ``RelaxNG`` class takes an ElementTree object to construct a Relax NG
  105. validator:
  106. .. sourcecode:: pycon
  107. >>> f = StringIO('''\
  108. ... <element name="a" xmlns="http://relaxng.org/ns/structure/1.0">
  109. ... <zeroOrMore>
  110. ... <element name="b">
  111. ... <text />
  112. ... </element>
  113. ... </zeroOrMore>
  114. ... </element>
  115. ... ''')
  116. >>> relaxng_doc = etree.parse(f)
  117. >>> relaxng = etree.RelaxNG(relaxng_doc)
  118. Alternatively, pass a filename to the ``file`` keyword argument to parse from
  119. a file. This also enables correct handling of include files from within the
  120. RelaxNG parser.
  121. You can then validate some ElementTree document against the schema. You'll get
  122. back True if the document is valid against the Relax NG schema, and False if
  123. not:
  124. .. sourcecode:: pycon
  125. >>> valid = StringIO('<a><b></b></a>')
  126. >>> doc = etree.parse(valid)
  127. >>> relaxng.validate(doc)
  128. True
  129. >>> invalid = StringIO('<a><c></c></a>')
  130. >>> doc2 = etree.parse(invalid)
  131. >>> relaxng.validate(doc2)
  132. False
  133. Calling the schema object has the same effect as calling its validate
  134. method. This is sometimes used in conditional statements:
  135. .. sourcecode:: pycon
  136. >>> invalid = StringIO('<a><c></c></a>')
  137. >>> doc2 = etree.parse(invalid)
  138. >>> if not relaxng(doc2):
  139. ... print("invalid!")
  140. invalid!
  141. If you prefer getting an exception when validating, you can use the
  142. ``assert_`` or ``assertValid`` methods:
  143. .. sourcecode:: pycon
  144. >>> relaxng.assertValid(doc2)
  145. Traceback (most recent call last):
  146. ...
  147. lxml.etree.DocumentInvalid: Did not expect element c there, line 1
  148. >>> relaxng.assert_(doc2)
  149. Traceback (most recent call last):
  150. ...
  151. AssertionError: Did not expect element c there, line 1
  152. If you want to find out why the validation failed in the second case, you can
  153. look up the error log of the validation process and check it for relevant
  154. messages:
  155. .. sourcecode:: pycon
  156. >>> log = relaxng.error_log
  157. >>> print(log.last_error)
  158. <string>:1:0:ERROR:RELAXNGV:RELAXNG_ERR_ELEMWRONG: Did not expect element c there
  159. You can see that the error (ERROR) happened during RelaxNG validation
  160. (RELAXNGV). The message then tells you what went wrong. You can also
  161. look at the error domain and its type directly:
  162. .. sourcecode:: pycon
  163. >>> error = log.last_error
  164. >>> print(error.domain_name)
  165. RELAXNGV
  166. >>> print(error.type_name)
  167. RELAXNG_ERR_ELEMWRONG
  168. Note that this error log is local to the RelaxNG object. It will only
  169. contain log entries that appeared during the validation.
  170. Similar to XSLT, there's also a less efficient but easier shortcut method to
  171. do one-shot RelaxNG validation:
  172. .. sourcecode:: pycon
  173. >>> doc.relaxng(relaxng_doc)
  174. True
  175. >>> doc2.relaxng(relaxng_doc)
  176. False
  177. libxml2 does not currently support the `RelaxNG Compact Syntax`_.
  178. However, the trang_ translator can convert the compact syntax to the
  179. XML syntax, which can then be used with lxml.
  180. .. _`RelaxNG Compact Syntax`:
  181. .. _trang: http://www.thaiopensource.com/relaxng/trang.html
  182. XMLSchema
  183. ---------
  184. lxml.etree also has XML Schema (XSD) support, using the class
  185. lxml.etree.XMLSchema. The API is very similar to the Relax NG and DTD
  186. classes. Pass an ElementTree object to construct a XMLSchema validator:
  187. .. sourcecode:: pycon
  188. >>> f = StringIO('''\
  189. ... <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  190. ... <xsd:element name="a" type="AType"/>
  191. ... <xsd:complexType name="AType">
  192. ... <xsd:sequence>
  193. ... <xsd:element name="b" type="xsd:string" />
  194. ... </xsd:sequence>
  195. ... </xsd:complexType>
  196. ... </xsd:schema>
  197. ... ''')
  198. >>> xmlschema_doc = etree.parse(f)
  199. >>> xmlschema = etree.XMLSchema(xmlschema_doc)
  200. You can then validate some ElementTree document with this. Like with RelaxNG,
  201. you'll get back true if the document is valid against the XML schema, and
  202. false if not:
  203. .. sourcecode:: pycon
  204. >>> valid = StringIO('<a><b></b></a>')
  205. >>> doc = etree.parse(valid)
  206. >>> xmlschema.validate(doc)
  207. True
  208. >>> invalid = StringIO('<a><c></c></a>')
  209. >>> doc2 = etree.parse(invalid)
  210. >>> xmlschema.validate(doc2)
  211. False
  212. Calling the schema object has the same effect as calling its validate method.
  213. This is sometimes used in conditional statements:
  214. .. sourcecode:: pycon
  215. >>> invalid = StringIO('<a><c></c></a>')
  216. >>> doc2 = etree.parse(invalid)
  217. >>> if not xmlschema(doc2):
  218. ... print("invalid!")
  219. invalid!
  220. If you prefer getting an exception when validating, you can use the
  221. ``assert_`` or ``assertValid`` methods:
  222. .. sourcecode:: pycon
  223. >>> xmlschema.assertValid(doc2)
  224. Traceback (most recent call last):
  225. ...
  226. lxml.etree.DocumentInvalid: Element 'c': This element is not expected. Expected is ( b )., line 1
  227. >>> xmlschema.assert_(doc2)
  228. Traceback (most recent call last):
  229. ...
  230. AssertionError: Element 'c': This element is not expected. Expected is ( b )., line 1
  231. Error reporting works as for the RelaxNG class:
  232. .. sourcecode:: pycon
  233. >>> log = xmlschema.error_log
  234. >>> error = log.last_error
  235. >>> print(error.domain_name)
  236. SCHEMASV
  237. >>> print(error.type_name)
  238. SCHEMAV_ELEMENT_CONTENT
  239. If you were to print this log entry, you would get something like the
  240. following. Note that the error message depends on the libxml2 version in
  241. use::
  242. <string>:1:ERROR::SCHEMAV_ELEMENT_CONTENT: Element 'c': This element is not expected. Expected is ( b ).
  243. Similar to XSLT and RelaxNG, there's also a less efficient but easier shortcut
  244. method to do XML Schema validation:
  245. .. sourcecode:: pycon
  246. >>> doc.xmlschema(xmlschema_doc)
  247. True
  248. >>> doc2.xmlschema(xmlschema_doc)
  249. False
  250. Schematron
  251. ----------
  252. Since version 2.0, lxml.etree features Schematron_ support, using the
  253. class lxml.etree.Schematron. It requires at least libxml2 2.6.21 to
  254. work. The API is the same as for the other validators. Pass an
  255. ElementTree object to construct a Schematron validator:
  256. .. sourcecode:: pycon
  257. >>> f = StringIO('''\
  258. ... <schema xmlns="http://www.ascc.net/xml/schematron" >
  259. ... <pattern name="Sum equals 100%.">
  260. ... <rule context="Total">
  261. ... <assert test="sum(//Percent)=100">Sum is not 100%.</assert>
  262. ... </rule>
  263. ... </pattern>
  264. ... </schema>
  265. ... ''')
  266. >>> sct_doc = etree.parse(f)
  267. >>> schematron = etree.Schematron(sct_doc)
  268. You can then validate some ElementTree document with this. Like with RelaxNG,
  269. you'll get back true if the document is valid against the schema, and false if
  270. not:
  271. .. sourcecode:: pycon
  272. >>> valid = StringIO('''\
  273. ... <Total>
  274. ... <Percent>20</Percent>
  275. ... <Percent>30</Percent>
  276. ... <Percent>50</Percent>
  277. ... </Total>
  278. ... ''')
  279. >>> doc = etree.parse(valid)
  280. >>> schematron.validate(doc)
  281. True
  282. >>> etree.SubElement(doc.getroot(), "Percent").text = "10"
  283. >>> schematron.validate(doc)
  284. False
  285. Calling the schema object has the same effect as calling its validate method.
  286. This is sometimes used in conditional statements:
  287. .. sourcecode:: pycon
  288. >>> is_valid = etree.Schematron(sct_doc)
  289. >>> if not is_valid(doc):
  290. ... print("invalid!")
  291. invalid!
  292. Note that libxml2 restricts error reporting to the parsing step (when creating
  293. the Schematron instance). There is not currently any support for error
  294. reporting during validation.