Package lxml :: Module treemigrator
[hide private]
[frames] | no frames]

Source Code for Module lxml.treemigrator

 1  """ 
 2  Ways to migrate trees between different ElementTree implementations. 
 3  """ 
 4   
5 -class TreeMigrator(object):
6 """The TreeMigrator copies a tree to an ElementTree implementation. 7 8 Pass the implementation to the constructor and call the migrator 9 on a tree. 10 """
11 - def __init__(ET_impl, makeelement=None):
12 if makeelement is None: 13 makeelement = ET_impl.Element 14 self.Element = makeelement 15 self.SubElement = ET_impl.SubElement
16
17 - def copyChildren(self, from_parent, to_parent):
18 for from_child in from_parent: 19 tag = from_child.tag 20 if not isinstance(tag, basestring): # skip Comments etc. 21 continue 22 to_child = self.SubElement( 23 to_parent, tag, from_child.attrib) 24 to_child.text = child.text 25 to_child.tail = child.tail 26 self.copyChildren(from_child, to_child)
27
28 - def __call__(self, from_root):
29 tag = from_root.tag 30 to_root = self.Element(tag, from_root.attrib) 31 to_root.text = from_root.text 32 to_root.tail = from_root.tail 33 if isinstance(tag, basestring): # skip Comments etc. 34 self.copyChildren(from_root, to_root) 35 return to_root
36 37
38 -class TreeReplicatorMaker(object):
39 """Fast tree mass replication. 40 41 Original implementation by Fredrik Lundh. 42 43 Note that the fastest way to deep copy an lxml XML tree is to use 44 the ``deepcopy()`` function from the standard Python ``copy`` 45 module. 46 """
47 - def __init__(ET_impl, makeelement=None):
48 if makeelement is None: 49 makeelement = ET_impl.Element 50 self.functions = { 51 "Element" : makeelement, 52 "SubElement" : ET_impl.SubElement, 53 "Comment" : ET_impl.Comment, 54 "PI" : ET_impl.PI, 55 }
56
57 - def make_clone_factory(self, elem):
58 if hasattr(elem, 'getroot'): 59 elem = elem.getroot() 60 def generate_elem(append, elem, level): 61 var = "e" + str(level) 62 arg = repr(elem.tag) 63 attrib = elem.attrib 64 if attrib: 65 arg += ", **%r" % attrib 66 if level == 1: 67 append(" e1 = Element(%s)" % arg) 68 else: 69 append(" %s = SubElement(e%d, %s)" % (var, level-1, arg)) 70 text = elem.text 71 if text: 72 append(" %s.text = %r" % (var, text)) 73 tail = elem.tail 74 if tail: 75 append(" %s.tail = %r" % (var, tail)) 76 for e in elem: 77 generate_elem(append, e, level+1)
78 # generate code for a function that creates a tree 79 output = ["def element_factory():"] 80 generate_elem(output.append, elem, 1) 81 output.append(" return e1") 82 # setup global function namespace 83 # create function object 84 namespace = self.functions.copy() 85 exec "\n".join(output) in namespace 86 return namespace["element_factory"]
87