from __future__ import print_function from xml.etree.ElementTree import * xml_text=""" John Cleese Lancelot Archie Leach Eric Idle Sir Robin Gunther Commander Clement """ ns = {'real_person': 'http://people.example.com', 'role': 'http://characters.example.com'} def printLastRoles(root): lastRoles = root.findall('./real_person:actor/role:character[last()]', ns) print('Found', len(lastRoles), 'last roles:') for lc in lastRoles: print('-->', lc.text) print('\nUsing fromstring') root = fromstring(xml_text) printLastRoles(root) print('\nUsing XMLParser and TreeBuilder') def myParser(): """ET XML parserer that stores tree in ElementWithDelegate instances""" return XMLParser(target=TreeBuilder()) root = fromstring(xml_text, parser=myParser()) printLastRoles(root) print('\nUsing XMLParser and TreeBuilder with Element subclass') class ElementSubclass(Element): def __init__(self, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.my_attribute = None def myParser(): """ET XML parserer that stores tree in ElementWithDelegate instances""" return XMLParser(target=TreeBuilder(element_factory=ElementSubclass)) root = fromstring(xml_text, parser=myParser()) printLastRoles(root)