0

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).

mzjn
  • 48,958
  • 13
  • 128
  • 248
Aryaman Gupta
  • 616
  • 1
  • 8
  • 20
  • 1
    lxml preserves all comments. Can you use lxml instead of ElementTree? See https://stackoverflow.com/q/45223696/407651 – mzjn May 18 '22 at 07:37

1 Answers1

1

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.

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34
  • 1
    Most comments can be preserved with ElementTree (the OP is clearly aware of this). See https://stackoverflow.com/a/59561426/407651. The question is about a special case: comments that occur before the start tag of the root element or after the end tag of the root element. – mzjn May 21 '22 at 11:11
  • That's what. It can not be done using Element Tree – Pavan Chandaka May 21 '22 at 14:28
  • The documentatation that you quoted is not the whole story. Your answer gives the impression that no comments can be preserved, which is not true. – mzjn May 21 '22 at 15:37
  • why -1 in my question? – Aryaman Gupta May 24 '22 at 11:00
  • 1
    Not sure who did it. It's a genuine question – Pavan Chandaka May 24 '22 at 15:32