1 """
2 Ways to migrate trees between different ElementTree implementations.
3 """
4
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):
16
18 for from_child in from_parent:
19 tag = from_child.tag
20 if not isinstance(tag, basestring):
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
36
37
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):
56
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
79 output = ["def element_factory():"]
80 generate_elem(output.append, elem, 1)
81 output.append(" return e1")
82
83
84 namespace = self.functions.copy()
85 exec "\n".join(output) in namespace
86 return namespace["element_factory"]
87