2015-09-03 48 views
1

我想一個標記添加到XML文件,請執行以下操作:到一個XML文件添加標籤使用DOM(minidom命名)

xmlFile = parse(paths) 
tag = xmlFile.createElement("tag") 
print "creado elemento materias" 
tag.setAttribute("tagname" , listaString) 
xmlFile.childNodes[0].appendChild(tag) 
xmlFile.toprettyxml() 

我的目標是添加一個字符串。 問題是代碼沒有返回錯誤,但沒有創建標籤。

我已經用作參考的問題: add element with attributes in minidom python

+0

它在Python 3.x的工作對我來說,就是你的問題是xmlFile.toprettyxml()不打印新的標籤?還是你在檢查文件本身,而不是到那裏? –

+0

我正在檢查文件本身,而不是標籤出現。我使用python 2.7.3 – Blunt

回答

1

xmlFile.toprettyxml()返回良好的XML作爲一個字符串,它不直接保存相當XML到文件。您需要手動進行保存。

示例 -

xmlFile = parse(paths) 
tag = xmlFile.createElement("tag") 
print "creado elemento materias" 
tag.setAttribute("tagname" , listaString) 
xmlFile.childNodes[0].appendChild(tag) 
with open('<newpath to file>','w') as f: 
    f.write(xmlFile.toprettyxml())