Creating a new xml document with python (minidom)
How to: Create a document; Create a element; Set element's attributes; Append an element on a document; Return a string representing the document; Write the document on a file.
Create a new document using the minidom library is really easy, you need only to import the minidom and after call one method, exactly equals the follow code:
from xml.dom import minidomActually the how-to could be finished here, but I will show a little bit more about the minidom.
# New document
xml = minidom.Document()
The next snippet shows how to create an element, set attributes and add this on our document created in the last step.
# Creates user element
userElem = xml.createElement("user")
# Set attributes to user element
userElem.setAttribute("name", "Sergio Oliveira")
userElem.setAttribute("nickname", "seocam")
userElem.setAttribute("email", "seocam@seocam.net")
userElem.setAttribute("photo","seocam.png")
# Append user element in xml document
xml.appendChild(userElem)
If you know the DOM specification nothing until here is new for you, but the next 2 snippets shows how to return a string and how to write a file with our xml document.
# Print the xml code
print xml.toxml("UTF-8")
fp = open("file.xml","w")
xml.writexml(fp, " ", "", "\n", "UTF-8")
# Method's stub
# writexml(self, writer, indent='', addindent='', newl='', encoding=None)
The result generated by both methods:
<?xml version="1.0" encoding="UTF-8"?>
<user email="seocam@seocam.net" name="Sergio Oliveira"
nickname="seocam" photo="seocam.png">