2011-04-18 69 views
4

我想在xml文件中注释一个特定的XML元素。我可以删除该元素,但我宁愿将其留下评论,以备后用。如何注释掉一个XML元素(使用minidom DOM实现)

我在那删除元素的那一刻使用的代码看起来是这样的:

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

我想修改此,使其评论元素出来而不是将其删除。

回答

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

你可以用beautifulSoup来做到这一点。阅读目标标签,创建适当的注释标记和replace目标标签

例如,创建注释标签:

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