Home > Enterprise >  How to append comment to XML file after XML declaration using Python?
How to append comment to XML file after XML declaration using Python?

Time:06-30

I create a root:

from xml.etree.ElementTree import Element, tostring

root = Element("root")

Then generating a string repr of XML:

xmlstr = tostring(root, encoding="utf8", method="xml")

And create my xml file:

        myFile = open(file, "w")
        myFile.write(xmlstr)
        myFile.close()

After all operations my file looks like that:

<?xml version="1.0" encoding="UTF-8"?>
<root>
</root>

What I should do to add some comments after xml declaration? Tried to use xml.etree.ElementTree.Comment but not sure how to do it properly. My desirable file should looks:

<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
<root>
</root>

Feel free to ask if you don't understand something. Thanks!

CodePudding user response:

Here is a suggestion. Provide both the XML declaration and the comment as a "header" string.

from xml.etree.ElementTree import Element, tostring

header = """<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
"""

root = Element("root")
xmlstr = tostring(root).decode()

# Create a file with header   xmlstr
with open("out.xml", "w", encoding='UTF-8') as out:
    out.write(header   xmlstr)

Resulting content in out.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- My comments -->
<root />
  • Related