如何使用ElementTree注释掉XML标签

3
我想将文本注释掉,类似这样:


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

非常感谢您的咨询。


我还没有处理过这个。看文档,我建议您先添加节点,获取新插入节点的句柄,然后在其上运行.Comment方法,保存树。 - shahkalpesh
只要我不必安装外部库,它可以是Minidom。 - fairyberry
@MartijnPieters:你是对的。我的意思是,获取现有节点的句柄并在其上运行.comment。我假设每个节点都是子树,可以这么说。 - shahkalpesh
快速查看minidom源代码可以发现,它确实不会转义注释内容。 - Martijn Pieters
@Martijn:我看到另一篇关于使用Python注释XML的帖子(https://dev59.com/ol_Va4cB1Zd3GeqPPAEn),但我不明白他们在做什么..你认为这个方法适用于我的情况吗? - fairyberry
显示剩余5条评论
1个回答

4

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

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

您有几个选项:

  • Upgrade to Python 2.7; it handles comment serialization correctly:

    $python2.7 -c "from xml.etree import ElementTree as ET; print ET.tostring(ET.Comment('<'))"
    <!--<-->
    
  • Install the external ElementTree library.

  • Use the Minidom (not recommended, the DOM API is overly verbose):

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

这是一个很好的答案,给你加上一分。 - timday

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接