Blunt
Blunt

Reputation: 549

Add tag to an XML file with Dom (minidom)

I want to add one tag to an XML file, do as follows:

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

My goal is to add a string. The problem is that the code did not return errors but does not create the tag.

I have used as reference the question: add element with attributes in minidom python

Upvotes: 1

Views: 1101

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 91009

xmlFile.toprettyxml() returns the pretty xml as a string, it does not directly save the pretty xml to file. You would manually need to do the saving.

Example -

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

Upvotes: 1

Related Questions