Search code examples
pythonxmlminidom

How to comment out an XML Element (using minidom DOM implementation)


I would like to comment out a specific XML element in an xml file. I could just remove the element, but I would prefer to leave it commented out, in case it's needed later.

The code I use at the moment that removes the element looks like this:

from xml.dom import minidom

doc = minidom.parse(myXmlFile)
for element in doc.getElementsByTagName('MyElementName'):
if element.getAttribute('name') in ['AttribName1', 'AttribName2']:
    element.parentNode.removeChild(element)
f = open(myXmlFile, "w")
f.write(doc.toxml())
f.close()

I would like to modify this so that it comments the element out rather then deleting it.


Solution

  • The following solution does exactly what I want.

    from xml.dom import minidom
    
    doc = minidom.parse(myXmlFile)
    for element in doc.getElementsByTagName('MyElementName'):
        if element.getAttribute('name') in ['AttrName1', 'AttrName2']:
            parentNode = element.parentNode
            parentNode.insertBefore(doc.createComment(element.toxml()), element)
            parentNode.removeChild(element)
    f = open(myXmlFile, "w")
    f.write(doc.toxml())
    f.close()