2013-01-12 13 views
2

我想註釋掉這樣的文字註釋XML 如何使用ElementTree的

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

任何意見,將不勝感激。

+0

我沒有工作這一點。看看文檔,我建議你先添加節點,獲取新插入的節點的句柄並運行.Comment方法,保存樹。 – shahkalpesh

+0

它可能是Minidom ..只要我不必安裝外部庫.. – fairyberry

+0

@MartijnPieters:你說得對。我的意思是,獲取現有節點的句柄並在其上運行.comment。我假設每個節點都是一個子樹。 – shahkalpesh

回答

1

包括在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") 
    
+0

這是一個很好的答案;有+1。 – timday