开发者

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

开发者 https://www.devze.com 2023-02-26 19:38 出处:网络
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 i开发者_如何转开发t\'s needed later.

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 i开发者_如何转开发t'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.


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()


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

For example, creating comment tag:

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

精彩评论

暂无评论...
验证码 换一张
取 消