本文介绍了如何注释掉一个 XML 元素(使用 minidom DOM 实现)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想注释掉 xml 文件中的特定 XML 元素.我可以删除该元素,但我更愿意将其注释掉,以防以后需要.
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.
推荐答案
以下解决方案正是我想要的.
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()
这篇关于如何注释掉一个 XML 元素(使用 minidom DOM 实现)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!