使用Dom(minidom)将标记添加到XML文件

时间:2015-09-03 03:45:10

标签: python xml dom

我想在XML文件中添加一个标记,执行如下操作:

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

1 个答案:

答案 0 :(得分: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())