Is there a way to add a comment on the first line of a XML file using ElementTree?

徘徊边缘 提交于 2019-12-08 05:45:37

问题


When generating a XML file using ElementTree, you can add a comment on the line below an element by using insert, e.g.

import xml.etree.ElementTree as ET
tree = ET.ElementTree("test.xml")  # modifying existing XML file
tree.getroot().insert(0, ET.Comment("Some comment..."))
tree.write("test_modified.xml")

This results in an output looking something like this:

<RootElement>
    <!--Some comment...--><NextElement>
    </NextElement>
</RootElement>

Is there a way to add a comment on the first line (before the root element) using ElementTree?

If not, what is the simplest way to achieve this by other means in Python?

来源:https://stackoverflow.com/questions/54791900/is-there-a-way-to-add-a-comment-on-the-first-line-of-a-xml-file-using-elementtre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!