1 # support for XMLSchema validation
2 from lxml.includes cimport xmlschema
5 cdef class XMLSchemaError(LxmlError):
6 """Base class of all XML Schema errors
9 cdef class XMLSchemaParseError(XMLSchemaError):
10 """Error while parsing an XML document as XML Schema.
13 cdef class XMLSchemaValidateError(XMLSchemaError):
14 """Error while validating an XML document with an XML Schema.
18 ################################################################################
21 cdef XPath _check_for_default_attributes = XPath(
22 u"boolean(//xs:attribute[@default or @fixed][1])",
23 namespaces={u'xs': u'http://www.w3.org/2001/XMLSchema'})
26 cdef class XMLSchema(_Validator):
27 u"""XMLSchema(self, etree=None, file=None)
28 Turn a document into an XML Schema validator.
30 Either pass a schema as Element or ElementTree, or pass a file or
31 filename through the ``file`` keyword argument.
33 Passing the ``attribute_defaults`` boolean option will make the
34 schema insert default/fixed attributes into validated documents.
36 cdef xmlschema.xmlSchema* _c_schema
38 cdef bint _has_default_attributes
39 cdef bint _add_attribute_defaults
42 self._has_default_attributes = True # play it safe
43 self._add_attribute_defaults = False
45 def __init__(self, etree=None, *, file=None, bint attribute_defaults=False):
46 cdef xmlschema.xmlSchemaParserCtxt* parser_ctxt
49 self._add_attribute_defaults = attribute_defaults
50 _Validator.__init__(self)
53 doc = _documentOrRaise(etree)
54 root_node = _rootNodeOrRaise(etree)
55 c_doc = _copyDocRoot(doc._c_doc, root_node._c_node)
56 self._doc = _documentFactory(c_doc, doc._parser)
57 parser_ctxt = xmlschema.xmlSchemaNewDocParserCtxt(c_doc)
58 elif file is not None:
60 filename = _encodeFilename(file)
61 parser_ctxt = xmlschema.xmlSchemaNewParserCtxt(_cstr(filename))
63 self._doc = _parseDocument(file, None, None)
64 parser_ctxt = xmlschema.xmlSchemaNewDocParserCtxt(self._doc._c_doc)
66 raise XMLSchemaParseError, u"No tree or file given"
68 if parser_ctxt is NULL:
71 xmlschema.xmlSchemaSetParserStructuredErrors(
72 parser_ctxt, _receiveError, <void*>self._error_log)
73 if self._doc is not None:
74 # calling xmlSchemaParse on a schema with imports or
75 # includes will cause libxml2 to create an internal
76 # context for parsing, so push an implied context to route
77 # resolve requests to the document's parser
78 __GLOBAL_PARSER_CONTEXT.pushImpliedContextFromParser(self._doc._parser)
80 self._c_schema = xmlschema.xmlSchemaParse(parser_ctxt)
81 if self._doc is not None:
82 __GLOBAL_PARSER_CONTEXT.popImpliedContext()
83 xmlschema.xmlSchemaFreeParserCtxt(parser_ctxt)
85 if self._c_schema is NULL:
86 raise XMLSchemaParseError(
87 self._error_log._buildExceptionMessage(
88 u"Document is not valid XML Schema"),
91 if self._doc is not None:
92 self._has_default_attributes = _check_for_default_attributes(self._doc)
93 self._add_attribute_defaults = attribute_defaults and self._has_default_attributes
95 def __dealloc__(self):
96 xmlschema.xmlSchemaFree(self._c_schema)
98 def __call__(self, etree):
99 u"""__call__(self, etree)
101 Validate doc using XML Schema.
103 Returns true if document is valid, false if not.
105 cdef xmlschema.xmlSchemaValidCtxt* valid_ctxt
107 cdef _Element root_node
111 assert self._c_schema is not NULL, "Schema instance not initialised"
112 doc = _documentOrRaise(etree)
113 root_node = _rootNodeOrRaise(etree)
115 valid_ctxt = xmlschema.xmlSchemaNewValidCtxt(self._c_schema)
116 if valid_ctxt is NULL:
120 if self._add_attribute_defaults:
121 xmlschema.xmlSchemaSetValidOptions(
122 valid_ctxt, xmlschema.XML_SCHEMA_VAL_VC_I_CREATE)
124 self._error_log.clear()
125 xmlschema.xmlSchemaSetValidStructuredErrors(
126 valid_ctxt, _receiveError, <void*>self._error_log)
128 c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
130 ret = xmlschema.xmlSchemaValidateDoc(valid_ctxt, c_doc)
131 _destroyFakeDoc(doc._c_doc, c_doc)
133 xmlschema.xmlSchemaFreeValidCtxt(valid_ctxt)
136 raise XMLSchemaValidateError(
137 u"Internal error in XML Schema validation.",
144 cdef _ParserSchemaValidationContext _newSaxValidator(
145 self, bint add_default_attributes):
146 cdef _ParserSchemaValidationContext context
147 context = _ParserSchemaValidationContext.__new__(_ParserSchemaValidationContext)
148 context._schema = self
149 context._add_default_attributes = (self._has_default_attributes and (
150 add_default_attributes or self._add_attribute_defaults))
155 cdef class _ParserSchemaValidationContext:
156 cdef XMLSchema _schema
157 cdef xmlschema.xmlSchemaValidCtxt* _valid_ctxt
158 cdef xmlschema.xmlSchemaSAXPlugStruct* _sax_plug
159 cdef bint _add_default_attributes
161 self._valid_ctxt = NULL
162 self._sax_plug = NULL
163 self._add_default_attributes = False
165 def __dealloc__(self):
168 xmlschema.xmlSchemaFreeValidCtxt(self._valid_ctxt)
170 cdef _ParserSchemaValidationContext copy(self):
171 assert self._schema is not None, "_ParserSchemaValidationContext not initialised"
172 return self._schema._newSaxValidator(
173 self._add_default_attributes)
175 cdef void inject_default_attributes(self, xmlDoc* c_doc):
176 # we currently need to insert default attributes manually
177 # after parsing, as libxml2 does not support this at parse
179 if self._add_default_attributes:
181 xmlschema.xmlSchemaValidateDoc(self._valid_ctxt, c_doc)
183 cdef int connect(self, xmlparser.xmlParserCtxt* c_ctxt, _BaseErrorLog error_log) except -1:
184 if self._valid_ctxt is NULL:
185 self._valid_ctxt = xmlschema.xmlSchemaNewValidCtxt(
186 self._schema._c_schema)
187 if self._valid_ctxt is NULL:
189 if self._add_default_attributes:
190 xmlschema.xmlSchemaSetValidOptions(
191 self._valid_ctxt, xmlschema.XML_SCHEMA_VAL_VC_I_CREATE)
192 if error_log is not None:
193 xmlschema.xmlSchemaSetValidStructuredErrors(
194 self._valid_ctxt, _receiveError, <void*>error_log)
195 self._sax_plug = xmlschema.xmlSchemaSAXPlug(
196 self._valid_ctxt, &c_ctxt.sax, &c_ctxt.userData)
198 cdef void disconnect(self):
199 if self._sax_plug is not NULL:
200 xmlschema.xmlSchemaSAXUnplug(self._sax_plug)
201 self._sax_plug = NULL
202 if self._valid_ctxt is not NULL:
203 xmlschema.xmlSchemaSetValidStructuredErrors(
204 self._valid_ctxt, NULL, NULL)
206 cdef bint isvalid(self):
207 if self._valid_ctxt is NULL:
209 return xmlschema.xmlSchemaIsValid(self._valid_ctxt)