Python - adding lxml top-level comments

I am using python2.6 and lxml, I want to add top level comments in xml like this

<?xml version='1.0' encoding='UTF-8'?>
<!--top level comment-->
<DCSubtitle/>

I use this addprevious () method for this, here is my code:

root = ET.Element("DCSubtitle")
root.addprevious(ET.Comment('top level comment'))
tree = ET.ElementTree(root)
tree.write(sys.stdout, pretty_print=True, xml_declaration=True, encoding='UTF-8')

But addprevious () seems not very logical, you need to add a second line and then add the first line, is there a better logical way to do this? Thank.

+4
source share
1 answer

It doesn't seem like that at all. Even lxml supporter Stefan Behnel suggested an additional method.

+2
source

Source: https://habr.com/ru/post/1536197/


All Articles