Skip to main content
 首页 » 编程设计

python之如何使用 ElementTree 注释掉 XML Tag>

2025年05月04日8think

我想注释掉这样的文本:

<name>cranberry</name> 

但是,我的脚本返回如下输出:

<!-- &lt;name&gt;cranberry&lt;/name&gt; --> 

我的脚本:

import xml.etree.ElementTree as ET 
from xml.etree.ElementTree import Comment 
 
tree = ET.parse(r"C:\sample.xml")  
root = tree.getroot()  
comment = ET.Comment("<name>cranberry</name>") 
root.insert(0,comment) 
tree.write(r"C:\sample1.xml") 

如有任何建议,我们将不胜感激。

请您参考如下方法:

Python 2.6 中包含的旧 ElementTree 库确实无条件地对注释中的数据进行 XML 转义:

$ python2.6 -c "from xml.etree import ElementTree as ET; print ET.tostring(ET.Comment('<'))" 
<!-- &lt; --> 

您有几个选择:

  • 升级到 Python 2.7;它正确处理评论序列化:

    $python2.7 -c "from xml.etree import ElementTree as ET; print ET.tostring(ET.Comment('<'))" 
    <!--<--> 
    
  • 安装外部 ElementTree图书馆。

  • 使用 Minidom(不推荐,DOM API 过于冗长):

    from xml.dom import minidom 
     
    doc = minidom.parse(r"C:\sample.xml") 
     
    comment = doc.createComment("<name>cranberry</name>") 
    doc.documentElement.appendChild(comment) 
     
    doc.writexml(r"C:\sample1.xml")