问题
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