0

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!

6
  • With lxml instead of ElementTree, you can use getprevious(). See stackoverflow.com/q/69652602/407651 and stackoverflow.com/q/23025245/407651 Commented Jun 29, 2022 at 11:38
  • Will check it :) Commented Jun 29, 2022 at 11:45
  • Sorry, I meant addprevious()! Commented Jun 29, 2022 at 11:49
  • It is possible to use xml.etree? Or only via lxml? Commented Jun 29, 2022 at 12:19
  • If you cannot use lxml, maybe you can read the file as plain text (not parsed XML) to add your comment after the first line, as suggested here: stackoverflow.com/a/69653155/407651 Commented Jun 29, 2022 at 12:58

1 Answer 1

0

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 />
Sign up to request clarification or add additional context in comments.

4 Comments

Will check it and let you know ;)
Almost perfect, <?xml version="1.0" encoding="UTF-8"?> <!-- My comments --> <root> As you can see, there are additionaly tabs. How can I remove them? Maybe strip func?
Not sure I understand. I don't get any tabs, but there are line breaks. The output is almost exactly what you call "My desirable file".
Yes, I made mistake by my side, everything is ok! ;) Thank you a lot for help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.