How to output elements in ElementTree PIParser?
If you want to preserve comments in an XML file with ElementTree, you can use the PIParser from http://effbot.org/zone/element-pi.htm
So if I have a file containing
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- This is a comment -->
<root>
  <foo>Hello World</foo>
</root>
<!-- That's all, folks -->

then the two comments will be preserved.
PIParser wraps the xml in another <document> node, so there is something to contain any comments that come outside the root node. The two comments are just two more elements contained in <document>.
But then how should I output the xml? I use code like this to output the contents of <document> without outputting the <document> tag itself:
file.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
doc = tree.getroot()

for child in doc:
  file.write(ET.tostring(child, encoding, method))
  file.write("\n")

Now, that seems to work if encoding is "utf-8". The tostring() method does not output one of those <?xml...?> lines, presumably because utf-8 is the default. That's why I wrote the <?xml...?> explicitly with file.write() above. But if encoding is "iso-8859-1" then tostring() puts a <?xml version="1.0" encoding="iso-8859-1"?> at the start of every element for which it is called! So I get one in front of every comment outside the root node, and another in front of the root node itself. I don't want that, I only want one at the top of the file. But instead of getting the xml as shown above, I get
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version='1.0' encoding='iso-8859-1'?>
<!-- This is a comment -->
<?xml version='1.0' encoding='iso-8859-1'?>
<root>
  <foo>Hello World</foo>
</root>
<?xml version='1.0' encoding='iso-8859-1'?>
<!-- That's all, folks -->

How do I control whether tostring() outputs a <?xml...?>? Or, should I be doing this another way?
