Python Forum
Python 3 Elementtree and Comment First - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python 3 Elementtree and Comment First (/thread-27082.html)



Python 3 Elementtree and Comment First - gw1500se - May-25-2020

I am building an xml file using ElemetTree but I need to insert the encoding comment first.
Quote:<!--version="1.0" encoding="UTF-8"-->
It seems like I have to create the root node first and then add the comment after. I need to figure out how to add the comment before the root node. Can someone tell me how to put the comment as the first line in the xml file using ElementTree? TIA.
ET.Comment(text='<!--version="1.0" encoding="UTF-8"-->')
root=ET.Element('root')
With this code the comment does not show up. If I add the comment using 'root.insert' after setting the root node, it show up as the 2nd line.


RE: Python 3 Elementtree and Comment First - Larz60+ - May-25-2020

Please show more code, everything up to and including the statements in your post would be good.


RE: Python 3 Elementtree and Comment First - ndc85430 - May-25-2020

Do you actually want to insert a comment, or do you really want to insert the XML declaration?


RE: Python 3 Elementtree and Comment First - gw1500se - May-25-2020

You are correct. XML declaration. I didn't know about that method. That fixed it. Thanks.