3

I would like to comment out a text like this:

<name>cranberry</name>

However, my script returns the output like this:

<!-- &lt;name&gt;cranberry&lt;/name&gt; -->

My Script:

import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Comment

tree = ET.parse(r"C:\sample.xml") 
root = tree.getroot() 
comment = ET.Comment("<name>cranberry</name>")
root.insert(0,comment)
tree.write(r"C:\sample1.xml")

Any advice would be appreciated.

10
  • I haven't worked on this. Looking at docs, I suggest you add the node first, get handle to the newly inserted node and run .Comment method on it, save the tree. Commented Jan 12, 2013 at 15:33
  • It could be Minidom..as long as I don't have to install external libraries.. Commented Jan 12, 2013 at 15:34
  • @MartijnPieters: You are right. what I mean is, get a handle to existing node and run .comment on it. I assume every node is a subtree, so to say. Commented Jan 12, 2013 at 15:35
  • A quick peek at the minidom source shows that it indeed won't escape comment contents. Commented Jan 12, 2013 at 15:35
  • @shahkalpesh: I know what you meant, but it won't work. :-) Commented Jan 12, 2013 at 15:37

1 Answer 1

4

The older ElementTree library included in Python 2.6 does indeed XML-escape data in comments unconditionally:

$ python2.6 -c "from xml.etree import ElementTree as ET; print ET.tostring(ET.Comment('<'))"
<!-- &lt; -->

You have a few options:

  • Upgrade to Python 2.7; it handles comment serialization correctly:

    $python2.7 -c "from xml.etree import ElementTree as ET; print ET.tostring(ET.Comment('<'))"
    <!--<-->
    
  • Install the external ElementTree library.

  • Use the Minidom (not recommended, the DOM API is overly verbose):

    from xml.dom import minidom
    
    doc = minidom.parse(r"C:\sample.xml")
    
    comment = doc.createComment("<name>cranberry</name>")
    doc.documentElement.appendChild(comment)
    
    doc.writexml(r"C:\sample1.xml")
    
Sign up to request clarification or add additional context in comments.

1 Comment

This is a fine answer; have a +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.