Question: Using ElementTree, how do I place a comment just below the XML declaration and above the root element?

I have tried `root.append(comment)`, but this places the comment as the last child of `root`. Can I append the comment to whatever is `root`'s parent?

Thanks.

Answer: 
Here is how a comment can be added in the wanted position (after XML declaration, before root element) with [lxml](http://lxml.de/index.html), using the [`addprevious()`](https://lxml.de/api/lxml.etree._Element-class.html#addprevious) method.

```
from lxml import etree

root = etree.fromstring('<root><x>y</x></root>')
comment = etree.Comment('This is a comment')
root.addprevious(comment)  # Add the comment as a preceding sibling

etree.ElementTree(root).write("out.xml",
                              pretty_print=True,
                              encoding="UTF-8",
                              xml_declaration=True)

```

Result (out.xml):

```
<?xml version='1.0' encoding='UTF-8'?>
<!--This is a comment-->
<root>
  <x>y</x>
</root>

```
Here

```
import xml.etree.ElementTree as ET

root = ET.fromstring('<root><e1><e2></e2></e1></root>')
comment = ET.Comment('Here is a  Comment')
root.insert(0, comment)
ET.dump(root)

```

output

```
<root><!--Here is a  Comment--><e1><e2 /></e1></root>

```