Faithfully Preserve Comments in Parsed XML

Tested with Python 2.7 and 3.5, the following code should work as intended.

#!/usr/bin/env python
# CommentedTreeBuilder.py
from xml.etree import ElementTree

class CommentedTreeBuilder(ElementTree.TreeBuilder):
    def comment(self, data):
        self.start(ElementTree.Comment, {})
        self.data(data)
        self.end(ElementTree.Comment)

Then, in the main code use

parser = ElementTree.XMLParser(target=CommentedTreeBuilder())

as the parser instead of the current one.

By the way, comments work correctly out of the box with lxml. That is, you can just do

import lxml.etree as ET
tree = ET.parse(filename)

without needing any of the above.

Leave a Comment