Python 在文档开头添加注释

Python 在文档开头添加注释,python,xml,comments,elementtree,Python,Xml,Comments,Elementtree,使用ElementTree,如何在XML声明下方和根元素上方放置注释 我尝试了root.append(comment),但这会将注释作为root的最后一个子项。我可以将注释附加到根用户的父用户吗 谢谢。这里 import xml.etree.ElementTree as ET root = ET.fromstring('<root><e1><e2></e2></e1></root>') comment = ET.Comme

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

我尝试了
root.append(comment)
,但这会将注释作为
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)
将xml.etree.ElementTree作为ET导入
root=ET.fromstring(“”)
comment=ET.comment('这里有一条注释')
root.insert(0,注释)
ET.dump(根目录)
输出

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

以下是如何使用方法将注释添加到所需位置(在XML声明之后,根元素之前)

从lxml导入etree
root=etree.fromstring('y')
comment=etree.comment('这是一条注释')
root.addprevious(comment)#将注释作为前面的同级添加
ElementTree(root).write(“out.xml”,
漂亮的印刷品=真的,
encoding=“UTF-8”,
xml_声明=True)
结果(out.xml):


Y

该注释是
的子注释,但OP希望它在
之前。这是不可能的。重复的,没有答案。您是正确的。这是一个副本。@mzjn谢谢链接。我从那里找到了一个解决方案的链接。不幸的是,这意味着稍微避开ElementTree。
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)
<?xml version='1.0' encoding='UTF-8'?>
<!--This is a comment-->
<root>
  <x>y</x>
</root>