XML Schema support on Zope 3


Fri 12 August 2005 By nuxeo

I started yesterday an XML Schema support for the ZopeInterface.  I
would like to be able to define my schema with XML Schemas definitions
instead of having to define them in Python (which is boring and
Python specific...).



The code is within the z3ecm repository: http://svn.nuxeo.org/trac/pub/browser/z3lab/zope/xmlschema/trunk/



See an example :


filepath is a path to an XML Schema definition as defined below :

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="description" type="xsd:string"/>
</xsd:schema>

>>> import zope.interface
>>> import zope.xmlschema
>>> class ITest(zope.interface.Interface):
... zope.xmlschema.set(filepath)


Now introspect the fields defined within the xsd. We will see two new
fields : title and description.

>>> names = list(ITest)
>>> names.sort()
>>> names
['description', 'title']

Now define a class implementing this interface.

>>> class Test(object):
... zope.interface.implements(ITest)
... title = ''
... description = ''
>>>

ITest is implemented by Test

>>> ITest.implementedBy(Test)
True

Let's create an instance of Test

>>> test = Test()

Defines potential values for the two fields

>>> title = u"Title field"
>>> description = u"Description field"

Now we get the fields from the interface:

>>> title_field = ITest.get('title')
>>> description_field = ITest.get('description')

Next we have to bind these fields to the context, so that instance-specific
information can be used for validation:

>>> title_bound = title_field.bind(test)
>>> description_bound = description_field.bind(test)

Now try to validate them :

>>> title_bound.validate(title)
>>> description_bound.validate(description)

You can see that once the schema is set on the interface the interface
behaves like if it had been defined in Python. Now let's dig into the XML
Schema specification and implements at least all the zope.schema features so
that zope.schema and zope.xmlschema will provide the same declarative
possibility.



Notice, this component uses lxml as core XML parser.



It's the first step toward XForms support on z3ecm :)


(Post originally written by Julien Anguenot on the old Nuxeo blogs.)


Category: Product & Development