0

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.

mzjn
  • 48,958
  • 13
  • 128
  • 248
posfan12
  • 2,541
  • 8
  • 35
  • 57
  • 1
    Duplicate of https://stackoverflow.com/q/54791900/407651, which has no answer. – mzjn Jul 04 '19 at 12:27
  • You are correct. It is a duplicate. – posfan12 Jul 04 '19 at 12:40
  • @mzjn Thanks for linking. I was able to find a link to a solution from there. https://stackoverflow.com/questions/8868248/how-to-create-doctype-with-pythons-celementtree Unfortunately, it means sidestepping ElementTree a little bit. – posfan12 Jul 04 '19 at 13:12

2 Answers2

2

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>
mzjn
  • 48,958
  • 13
  • 128
  • 248
-1

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>
balderman
  • 22,927
  • 7
  • 34
  • 52