tuples within tuples

Duncan Booth duncan.booth at invalid.invalid
Fri Oct 26 10:00:14 EDT 2007


korovev76 at gmail.com wrote:

> 
> [cut]
>>
>> Without a better example or explanation of what you are trying to do
>> it is difficult
> 
> You're right.
> Actually i'm parsing an xml file using pyrxp, which returns something
> like this:
> (tagName, attributes, list_of_children, spare)
> Where list_of_children might "be a list with elements that are 4-
> tuples or plain strings".
> 
> In other terms, if I have something like this:
> ('<tagA><tagB>bobloblaw</tagB></tagA>')
> it's parsed like this:
> ('tagA', None, [('tagB', None, ['bobloblaw], None)], None)...
> 
> Fact is that my xml is much more deep... and I'm not sure how to
> resolve it
> 
Probably you want some sort of visitor pattern.

e.g. (warning untested pseudo code ahead)

def walkTree(tree, visitor):
    tag, attrs, children, spare = tree
    fn = getattr(visitor, 'visit_'+tag, None)
    if not fn: fn = visitor.visitDefault
    fn(tag, attrs, children, spare)

    for child in children:
        if isinstance(child, tuple):
            walktree(child, visitor)
        else:
            visitor.visitContent(child)

class Visitor:
   def visitDefault(self, t, a, c, s): pass
   def visitContent(self, c): pass

... then when you want to use it you subclass Visitor adding appropriate 
visit_tagA, visit_tabB methods for the tags which interest you. You walk 
the tree, and store whatever you want to save in your visitor subclass 
instance.




More information about the Python-list mailing list