如何注释XML元素(使用minidom DOM实现)
我想在一个XML文件中把某个特定的元素注释掉。我可以直接把这个元素删掉,但我更希望把它注释掉,这样以后如果需要的话还可以用到。
我现在用的代码是直接删除这个元素,代码如下:
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()
我想把这段代码改成注释掉这个元素,而不是直接删除它。
2 个回答
0
你可以使用beautifulSoup来实现这个功能。首先找到你想要的标签,然后创建一个合适的注释标签,最后用这个注释标签替换掉原来的标签。
比如,创建注释标签的代码如下:
from BeautifulSoup import BeautifulSoup
hello = "<!--Comment tag-->"
commentSoup = BeautifulSoup(hello)
5
下面的解决方案正好满足我的需求。
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()