posfan12
posfan12

Reputation: 2651

Add comment to beginning of document

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.

Upvotes: 1

Views: 1583

Answers (2)

mzjn
mzjn

Reputation: 50977

Here is how a comment can be added in the wanted position (after XML declaration, before root element) with lxml, using the 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>

Upvotes: 3

balderman
balderman

Reputation: 23815

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>

Upvotes: -1

Related Questions