我想评论出这样的文字:
<name>cranberry</name>
但是,我的脚本会返回如下输出:
<!-- <name>cranberry</name> -->
我的剧本:
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")
任何建议都将受到赞赏。
答案 0 :(得分:1)
Python 2.6中包含的旧ElementTree库确实无条件地在注释中使用XML转义数据:
$ python2.6 -c "from xml.etree import ElementTree as ET; print ET.tostring(ET.Comment('<'))"
<!-- < -->
您有几个选择:
升级到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")