![](/img/trans.png)
[英]How to parse XML in python using ElementTree (find content of a tag)
[英]How To Comment Out XML <Tag> using ElementTree
我想注釋掉這樣的文本:
<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")
任何意見,將不勝感激。
實際上,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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.