[lxml-dev] About objectify
David Soulayrol
dsoulayrol at free.fr
Tue Jan 22 23:28:58 CET 2008
Hello,
Le mardi 22 janvier 2008 à 17:31 +0100, jholg at gmx.de a écrit :
> Hi,
>
> > I should have written I'd like to define a complex type, as stated
> > in
> > the end of the following chapter.
> >
> > http://codespeak.net/lxml/objectify.html#how-data-types-are-matched
> >
> Hm, it is not really a complex type (in XML Schema terms), but rather
> a custom simple data type.
>
>
> >
> > In my case, writing a type checker would be impossible - or very
> > difficult. I understand I can also use a py:pytype attribute, but
> > I'd like to try the xsi namespace if possible.
>
> Have you tried registering your custom type as an xmlSchemaType, as
> in:
>
> >>> my_strange_type.xmlSchemaTypes = ("myns:mytypename",)
All this was a bit fuzzy to me. I had the time to dig more, and here is
a very simple file I wrote to proceed to some tests:
---%<------%<------%<------%<---
<?xml version="1.0" encoding="ISO-8859-15"?>
<site xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:type='site'>
<title xsi:type='title'>Achille 2.0</title>
<value xsi:type='long'>2</value>
</site>
---%<------%<------%<------%<---
And below the code I've written to parse it:
---%<------%<------%<------%<---
from lxml import etree
from lxml import objectify
class Configuration(objectify.ObjectifiedDataElement):
pass
class MyString(objectify.ObjectifiedDataElement):
pass
configuration_type = objectify.PyType('configuration', None,
Configuration)
string_type = objectify.PyType('MyString', None, MyString)
configuration_type.xmlSchemaTypes = ('site',)
string_type.xmlSchemaTypes = ('title',)
configuration_type.register()
string_type.register()
lParser = etree.XMLParser(remove_blank_text=True)
lLookup = objectify.ObjectifyElementClassLookup()
lParser.setElementClassLookup(lLookup)
lFile = open('test.xml', 'r')
lTree = etree.parse(lFile, lParser)
print objectify.dump(lTree.getroot())
---%<------%<------%<------%<---
Here is the result:
$ python ./try_objectify.py
site = None [ObjectifiedElement]
* xsi:type = 'site'
title = Achille 2.0 [MyString]
* xsi:type = 'title'
value = 2L [LongElement]
* xsi:type = 'long'
So I managed to get some success, but here are some remaining questions.
- Why is the root element still an ObjectifiedElement instance ? It
seems to me I applied the same rules for both of my defined types.
- Is there a way to specify the xsi:type in a schema sheet ? This
question may sound stupid, but I'm still learning the XSD spec, and I
wonder if objectify could rely entirely on the schema, without the need
to add anything in the XML document itself.
> Good luck,
Thanks for your attention,
--
David Soulayrol <dsoulayrol at free.fr>
More information about the lxml-dev
mailing list