How to comment on an XML element (using a mini-DOM implementation)

I would like to comment on a specific XML element in an XML file. I could just delete the item, but I would prefer to leave it commented, if necessary later.

The code that I use at the time of deleting the item is as follows:

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 change this so that he comments on the element, rather than deleting it.

+4
source share
2 answers

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() 
+5
source

You can do it with beautifulSoup . Read the target tag, create the corresponding comment tag, and replace the target tag

For example, creating a comment tag:

 from BeautifulSoup import BeautifulSoup hello = "<!--Comment tag-->" commentSoup = BeautifulSoup(hello) 
0
source

All Articles