Reputation: 642
I am updating the xml file using python xml module and I want to preserve all the comments, using insert_comment variable is preserving the comments inside root element but removing outside/end of the xml file.
Is there any way to save those comments along with inner ones?
Below is the answers I found.
Python 3.8 added the insert_comments argument to TreeBuilder which:
class xml.etree.ElementTree.TreeBuilder(element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, insert_pis=False)
When insert_comments and/or insert_pis is true, comments/pis will be inserted into the tree if they appear within root element the (but not outside of it).
Upvotes: 0
Views: 1021
Reputation: 12771
As your question tag contains "elementtree", this answer is specific about that.
The solution you are expecting is may not be possible due to default design of ElementTree XMLParser
. The parser skips over the comments. Look into below official documented snippet.
Note that XMLParser skips over comments in the input instead of creating comment objects for them. An ElementTree will only contain comment nodes if they have been inserted into to the tree using one of the Element methods.
Please find the above content in below documentation link.
https://docs.python.org/3/library/xml.etree.elementtree.html
search for xml.etree.ElementTree.Comment
in above link.
Upvotes: 1