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

ε祈祈猫儿з 提交于 2019-12-21 02:43:44

问题


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.


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/5699745/how-to-comment-out-an-xml-element-using-minidom-dom-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!