【问题标题】:How to comment out an XML Element (using minidom DOM implementation)如何注释掉一个 XML 元素(使用 minidom DOM 实现)
【发布时间】:2011-04-18 07:24:17
【问题描述】:

我想注释掉 xml 文件中的特定 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()

我想对此进行修改,以便将元素取出而不是删除。

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    以下解决方案正是我想要的。

    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】:

      您可以使用beautifulSoup 完成此操作。读取目标标签,创建相应的评论标签和replace目标标签

      例如创建评论标签:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-01
        • 2014-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多