Getting contents of an lxml.objectify comment
<p>I have an XML file that I'm reading using python's <code>lxml.objectify</code> library.</p>

<p>I'm not finding a way of getting the contents of an XML comment:</p>

<pre><code>&lt;data&gt;
  &lt;!--Contents 1--&gt;
  &lt;some_empty_tag/&gt;
  &lt;!--Contents 2--&gt;
&lt;/data&gt;
</code></pre>

<p>I'm able to retrieve the comment (is there a better way? <code>xml.comment[1]</code> does not seem to work):</p>

<pre><code>xml = objectify.parse(the_xml_file).getroot()
for c in xml.iterchildren(tag=etree.Comment):
   print c.???? # how do i print the contets of the comment?
   # print c.text  # does not work
   # print str(c)  # also does not work
</code></pre>

<p>What is the correct way?</p>

<p>You just need to convert the child back to string to extract the comments, like this:</p>

<pre><code>In [1]: from lxml import etree, objectify

In [2]: tree = objectify.fromstring("""&lt;data&gt;
   ...:   &lt;!--Contents 1--&gt;
   ...:   &lt;some_empty_tag/&gt;
   ...:   &lt;!--Contents 2--&gt;
   ...: &lt;/data&gt;""")

In [3]: for node in tree.iterchildren(etree.Comment):
   ...:     print(etree.tostring(node))
   ...:
b'&lt;!--Contents 1--&gt;'
b'&lt;!--Contents 2--&gt;'
</code></pre>

<p>Of course you may want to strip the unwanted wrapping.</p>

python lxml.objectify