@@ -151,6 +151,49 @@ def serializeElement(element, indent=0):
151
151
152
152
return "\n " .join (rv )
153
153
154
+ def write (element ):
155
+ """Serialize an element and its child nodes to a string"""
156
+ rv = []
157
+ finalText = None
158
+ def serializeElement (element ):
159
+ if element .tag is DocumentType :
160
+ rv .append ("<!DOCTYPE %s>\n " % (element .text ,))
161
+ elif element .tag is Document :
162
+ if element .text :
163
+ rv .append (element .text )
164
+ if element .tail :
165
+ finalText = element .tail
166
+
167
+ for child in element .getchildren ():
168
+ serializeElement (child )
169
+
170
+ elif element .tag is Comment :
171
+ rv .append ("<!-- %s -->\n " % (element .text ,))
172
+ else :
173
+ if not element .attrib :
174
+ rv .append ("<%s>" % (element .tag ,))
175
+ else :
176
+ attr = " " .join (["%s=\" %s\" " % (name , value )
177
+ for name , value in element .attrib .iteritems ()])
178
+ rv .append ("<%s %s>" % (element .tag , attr ))
179
+ if element .text :
180
+ rv .append (element .text )
181
+
182
+ for child in element .getchildren ():
183
+ serializeElement (child )
184
+
185
+ rv .append ("</%s>\n " % (element .tag ,))
186
+
187
+ if element .tail :
188
+ rv .append (element .tail + "\n " )
189
+
190
+ serializeElement (element )
191
+
192
+ if finalText is not None :
193
+ rv .append ("%s\" " % (' ' * 2 , finalText ))
194
+
195
+ return "" .join (rv )
196
+
154
197
class TreeBuilder (_base .TreeBuilder ):
155
198
documentClass = Document
156
199
doctypeClass = DocumentType
0 commit comments