I have a xml file containing one interesting comment, and I would like to parse it.
Here I discovered how I can handle comments, but I don't know how to use them from my main app.
#!/usr/bin/python3
import xml.etree.ElementTree as ET
with open('xml_with_comments.xml', 'w') as f:
f.write('''<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<blah>node 1</blah>
<!-- secret_content: Hello! -->
<blah>node 2</blah>
<!-- A standard comment -->
<blah>node 3</blah>
</root>
''')
class TreeBuilderWithComments(ET.TreeBuilder):
def comment(self, data):
if data.startswith(' secret_content: '):
self.start(ET.Comment, {})
self.data(data)
self.end(ET.Comment)
print('Secret content from TreeBuilderWithComments: ' + data[17:-1])
root = ET.parse('xml_with_comments.xml', parser=ET.XMLParser(target=TreeBuilderWithComments())).getroot()
for blah in root.findall('blah'):
print(blah.text)
This outputs:
Secret content from TreeBuilderWithComments: Hello!
node 1
node 2
node 3
Now I would like to do something like print(root.get_secret_content()), which should print the first comment of the file begining by ' secret_content: '.