您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

174 行
5.9 KiB

  1. # support for Schematron validation
  2. from lxml.includes cimport schematron
  3. cdef class SchematronError(LxmlError):
  4. """Base class of all Schematron errors.
  5. """
  6. cdef class SchematronParseError(SchematronError):
  7. """Error while parsing an XML document as Schematron schema.
  8. """
  9. cdef class SchematronValidateError(SchematronError):
  10. """Error while validating an XML document with a Schematron schema.
  11. """
  12. ################################################################################
  13. # Schematron
  14. cdef class Schematron(_Validator):
  15. """Schematron(self, etree=None, file=None)
  16. A Schematron validator.
  17. Pass a root Element or an ElementTree to turn it into a validator.
  18. Alternatively, pass a filename as keyword argument 'file' to parse from
  19. the file system.
  20. Schematron is a less well known, but very powerful schema language. The main
  21. idea is to use the capabilities of XPath to put restrictions on the structure
  22. and the content of XML documents. Here is a simple example::
  23. >>> schematron = Schematron(XML('''
  24. ... <schema xmlns="http://www.ascc.net/xml/schematron" >
  25. ... <pattern name="id is the only permitted attribute name">
  26. ... <rule context="*">
  27. ... <report test="@*[not(name()='id')]">Attribute
  28. ... <name path="@*[not(name()='id')]"/> is forbidden<name/>
  29. ... </report>
  30. ... </rule>
  31. ... </pattern>
  32. ... </schema>
  33. ... '''))
  34. >>> xml = XML('''
  35. ... <AAA name="aaa">
  36. ... <BBB id="bbb"/>
  37. ... <CCC color="ccc"/>
  38. ... </AAA>
  39. ... ''')
  40. >>> schematron.validate(xml)
  41. 0
  42. >>> xml = XML('''
  43. ... <AAA id="aaa">
  44. ... <BBB id="bbb"/>
  45. ... <CCC/>
  46. ... </AAA>
  47. ... ''')
  48. >>> schematron.validate(xml)
  49. 1
  50. Schematron was added to libxml2 in version 2.6.21. Before version 2.6.32,
  51. however, Schematron lacked support for error reporting other than to stderr.
  52. This version is therefore required to retrieve validation warnings and
  53. errors in lxml.
  54. """
  55. cdef schematron.xmlSchematron* _c_schema
  56. cdef xmlDoc* _c_schema_doc
  57. def __init__(self, etree=None, *, file=None):
  58. cdef _Document doc
  59. cdef _Element root_node
  60. cdef xmlNode* c_node
  61. cdef char* c_href
  62. cdef schematron.xmlSchematronParserCtxt* parser_ctxt = NULL
  63. _Validator.__init__(self)
  64. if not config.ENABLE_SCHEMATRON:
  65. raise SchematronError, \
  66. "lxml.etree was compiled without Schematron support."
  67. import warnings
  68. warnings.warn(
  69. "The (non-ISO) Schematron feature is deprecated and will be removed from libxml2 and lxml. "
  70. "Use 'lxml.isoschematron' instead.",
  71. DeprecationWarning,
  72. )
  73. if etree is not None:
  74. doc = _documentOrRaise(etree)
  75. root_node = _rootNodeOrRaise(etree)
  76. self._c_schema_doc = _copyDocRoot(doc._c_doc, root_node._c_node)
  77. parser_ctxt = schematron.xmlSchematronNewDocParserCtxt(self._c_schema_doc)
  78. elif file is not None:
  79. filename = _getFilenameForFile(file)
  80. if filename is None:
  81. # XXX assume a string object
  82. filename = file
  83. filename = _encodeFilename(filename)
  84. with self._error_log:
  85. orig_loader = _register_document_loader()
  86. parser_ctxt = schematron.xmlSchematronNewParserCtxt(_cstr(filename))
  87. _reset_document_loader(orig_loader)
  88. else:
  89. raise SchematronParseError, "No tree or file given"
  90. if parser_ctxt is NULL:
  91. if self._c_schema_doc is not NULL:
  92. tree.xmlFreeDoc(self._c_schema_doc)
  93. self._c_schema_doc = NULL
  94. raise MemoryError()
  95. try:
  96. with self._error_log:
  97. orig_loader = _register_document_loader()
  98. self._c_schema = schematron.xmlSchematronParse(parser_ctxt)
  99. _reset_document_loader(orig_loader)
  100. finally:
  101. schematron.xmlSchematronFreeParserCtxt(parser_ctxt)
  102. if self._c_schema is NULL:
  103. raise SchematronParseError(
  104. "Document is not a valid Schematron schema",
  105. self._error_log)
  106. def __dealloc__(self):
  107. schematron.xmlSchematronFree(self._c_schema)
  108. if self._c_schema_doc is not NULL:
  109. tree.xmlFreeDoc(self._c_schema_doc)
  110. def __call__(self, etree):
  111. """__call__(self, etree)
  112. Validate doc using Schematron.
  113. Returns true if document is valid, false if not."""
  114. cdef _Document doc
  115. cdef _Element root_node
  116. cdef xmlDoc* c_doc
  117. cdef schematron.xmlSchematronValidCtxt* valid_ctxt
  118. cdef int ret
  119. assert self._c_schema is not NULL, "Schematron instance not initialised"
  120. doc = _documentOrRaise(etree)
  121. root_node = _rootNodeOrRaise(etree)
  122. valid_ctxt = schematron.xmlSchematronNewValidCtxt(
  123. self._c_schema, schematron.XML_SCHEMATRON_OUT_ERROR)
  124. if valid_ctxt is NULL:
  125. raise MemoryError()
  126. try:
  127. self._error_log.clear()
  128. # Need a cast here because older libxml2 releases do not use 'const' in the functype.
  129. schematron.xmlSchematronSetValidStructuredErrors(
  130. valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
  131. c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
  132. with nogil:
  133. ret = schematron.xmlSchematronValidateDoc(valid_ctxt, c_doc)
  134. _destroyFakeDoc(doc._c_doc, c_doc)
  135. finally:
  136. schematron.xmlSchematronFreeValidCtxt(valid_ctxt)
  137. if ret == -1:
  138. raise SchematronValidateError(
  139. "Internal error in Schematron validation",
  140. self._error_log)
  141. if ret == 0:
  142. return True
  143. else:
  144. return False