Creating custom binding class for renaming nodes

5 views
Skip to first unread message

meppum

unread,
Sep 1, 2009, 11:06:57 PM9/1/09
to akara
I have some xml that I cannot change the names of the nodes. I'd like
to create a custom binding class so that I can create more API
friendly names to retrieve the data, or do some post processing on the
data.

The only example I could find does not act on the XML that is being
parsed by the bindery class (http://wiki.xml3k.org/Amara/Manual#custom-
binding-classes). Could someone please provide a binding class method
that would allow me to access a node by a different name, such as:


XML = '<xml>
<someTerribleName>
'this is a test'
</someTerribleName>
</xml>'

doc = amara.parse(XML, binding_classes={(None, u'foo'):
specialized_class})

doc.someNiceName # outputs 'this is a test'


Thanks.

Uche Ogbuji

unread,
Sep 3, 2009, 10:09:43 PM9/3/09
to ak...@googlegroups.com


Hi.  So this is a list for the new version, Amara 2.x.  It looks as if you're using the old version.  In the old version this was not as straightforward as I'd like.  In fact your best bet would have been monkey-patching the bindery handler.

In the new version it's a lot easier

XML = '''<spam>

  <someTerribleName>
     'this is a test'
  </someTerribleName>
</spam>'''

from amara import bindery

class smart_entity(bindery.nodes.entity_base):
    NAME_MAPPING = {'someTerribleName': 'someNiceName'}
    def xml_pyname(self, ns, local, parent=None, iselement=True):
        pyname = bindery.nodes.entity_base.xml_pyname(self, ns, local, parent, iselement)
        return self.NAME_MAPPING.get(pyname, pyname)

doc = bindery.parse(XML, entity_factory=smart_entity)

print unicode(doc.spam.someNiceName) # outputs 'this is a test'


So I hope you're able to use the 2.0 version instead.  There is a lot of reason to do so, even though it's officially still alpha.

I do think I'd like to cut out a few more steps from the above, but I think for now it's not so bad.


--
Uche Ogbuji                       http://uche.ogbuji.net
Founding Partner, Zepheira        http://zepheira.com
Linked-in profile: http://www.linkedin.com/in/ucheogbuji
Articles: http://uche.ogbuji.net/tech/publications/
Friendfeed: http://friendfeed.com/uche
Twitter: http://twitter.com/uogbuji
Join me at Balisage:
* http://www.balisage.net/
Reply all
Reply to author
Forward
0 new messages