在文档开头添加注释

Add comment to beginning of document

如何使用 ElementTree 在 XML 声明下方和根元素上方放置注释?

我试过 root.append(comment),但这会将评论作为 root 的最后一个子项。我可以将评论附加到 root 的父项吗?

谢谢。

这里

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)

输出

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

下面是如何使用 lxml, using the addprevious() 方法在所需位置(XML 声明之后,根元素之前)添加注释。

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)

结果(out.xml):

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