1

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

Community
  • 1
  • 1
Blunt
  • 529
  • 1
  • 8
  • 14
  • It worked for me in Python 3.x , is your issue that xmlFile.toprettyxml() is not printing the new tag? Or is it that you are checking in the file itself, and its not coming there? – Anand S Kumar Sep 03 '15 at 04:02
  • I'm checking the file itself, not the label appears. I use python 2.7.3 – Blunt Sep 03 '15 at 04:25

1 Answers1

1

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())
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176