2010-03-18 109 views
3

我正在嘗試查找如何更改現有xml文件元素值的示例。使用DOM更改現有XML文件中的元素值

使用下面的XML例子:

<book> 
    <title>My Book</title> 
    <author>John Smith</author> 
</book> 

如果我想使用DOM在Python腳本,以取代author元素值「約翰·史密斯」與「吉姆·約翰遜,我怎麼會去這樣做呢?我試圖尋找這方面的例子,但沒有這樣做。任何幫助將不勝感激。

問候, Rylic

回答

5

。假定

s = ''' 
<book> 
    <title>My Book</title> 
    <author>John Smith</author> 
</book>''' 

DOM會是什麼樣子:

from xml.dom import minidom 

dom = minidom.parseString(s) # or parse(filename_or_file) 
for author in dom.getElementsByTagName('author'): 
    author.childNodes = [dom.createTextNode("Jane Smith")] 

但我鼓勵你尋找到ElementTree的,它與XML一件輕而易舉的工作:

from xml.etree import ElementTree 

et = ElementTree.fromstring(s) # or parse(filename_or_file) 
for author in et.findall('author'): 
    author.text = "Jane Smith" 
+0

非常感謝您的幫助。按照你的建議使用ElementTree,並且它工作正常。我可以用需要的改變寫入xml文件。我確實注意到,當文件被寫入時,文件被鎖定。我假定該文件仍然可以寫入。在用ElementTree寫入文件之後,有沒有解密文件的方法? – user296793 2010-03-19 14:48:26

+0

@ rylic38你如何處理寫入文件?你可以在http://pastie.org/上粘貼代碼示例嗎? – Callahad 2010-03-19 15:30:51

+0

pastie.org不幸在工作中無法訪問。我將在這裏添加: 進口OS 導入XML 從xml.etree進口的ElementTree作爲等 路徑= 「C:\\ \\溫度books.xml」 中 樹= et.parse(路徑) 用於tree.findall(「作者」)作者: \t author.text =「Jane Doe的」 \t tree.write(路徑) 當運行此逐行在命令行中,XML文件的寫入到,但被鎖定。如果我退出python,文件被釋放,然後我可以看到更改。 – user296793 2010-03-19 15:50:52

相關問題