I\'d like to preserve comments as faithfully as possible while manipulating XML.
I managed to preserve comments, but the contents are getting XML-escaped.
Martin's Code didn't work for me. I modified the same with the following which works as intended.
import xml.etree.ElementTree as ET
class CommentedTreeBuilder(ET.XMLTreeBuilder):
def __init__(self, *args, **kwargs):
super(CommentedTreeBuilder, self).__init__(*args, **kwargs)
self._parser.CommentHandler = self.comment
def comment(self, data):
self._target.start(ET.Comment, {})
self._target.data(data)
self._target.end(ET.Comment)
This is the test
parser=CommentedTreeBuilder()
tree = ET.parse(filename, parser)
tree.write('out.xml')