@@ -36,7 +36,7 @@ def __init__(self):
36
36
self ._childNodes = []
37
37
38
38
def appendChild (self , element ):
39
- warnings . warn ( "lxml does not support comments as siblings of the root node" , DataLossWarning )
39
+ self . _elementTree . getroot (). addnext ( element . _element )
40
40
41
41
def _getChildNodes (self ):
42
42
return self ._childNodes
@@ -50,11 +50,19 @@ def serializeElement(element, indent=0):
50
50
if not hasattr (element , "tag" ):
51
51
rv .append ("#document" )
52
52
if element .docinfo .internalDTD :
53
- dtd_str = element .docinfo .doctype
54
- if not dtd_str :
53
+ if not (element .docinfo .public_id or element .docinfo .system_url ):
55
54
dtd_str = "<!DOCTYPE %s>" % element .docinfo .root_name
55
+ else :
56
+ dtd_str = """<!DOCTYPE %s PUBLIC "%s" "%s">""" % (
57
+ element .docinfo .root_name , element .docinfo .public_id ,
58
+ element .docinfo .system_url )
56
59
rv .append ("|%s%s" % (' ' * (indent + 2 ), dtd_str ))
57
- serializeElement (element .getroot (), indent + 2 )
60
+ next_element = element .getroot ()
61
+ while next_element .getprevious () is not None :
62
+ next_element = next_element .getprevious ()
63
+ while next_element is not None :
64
+ serializeElement (next_element , indent + 2 )
65
+ next_element = next_element .getnext ()
58
66
elif type (element .tag ) == type (etree .Comment ):
59
67
rv .append ("|%s<!-- %s -->" % (' ' * indent , element .text ))
60
68
else :
@@ -136,6 +144,7 @@ def __init__(self, fullTree = False):
136
144
def reset (self ):
137
145
_base .TreeBuilder .reset (self )
138
146
self .insertComment = self .insertCommentInitial
147
+ self .initial_comments = []
139
148
self .doctype = None
140
149
141
150
def testSerializer (self , element ):
@@ -159,7 +168,7 @@ def insertDoctype(self, name, publicId, systemId):
159
168
self .doctype = doctype
160
169
161
170
def insertCommentInitial (self , data , parent = None ):
162
- warnings . warn ( "lxml does not support comments as siblings of the root node" , DataLossWarning )
171
+ self . initial_comments . append ( data )
163
172
164
173
def insertRoot (self , name ):
165
174
"""Create the document root"""
@@ -181,6 +190,10 @@ def insertRoot(self, name):
181
190
print docStr
182
191
raise
183
192
193
+ #Append the initial comments:
194
+ for comment_data in self .initial_comments :
195
+ root .addprevious (etree .Comment (comment_data ))
196
+
184
197
#Create the root document and add the ElementTree to it
185
198
self .document = self .documentClass ()
186
199
self .document ._elementTree = root .getroottree ()
0 commit comments