xml문서 만들기

from xml.dom import minidom

# New document
xml = minidom.Document()

Actually the how-to could be finished here, but I will show a little bit more about the minidom.

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”>

출처 http://www.seocam.net/how-tos/creating-a-new-xml-document-with-python-minidom

답글 남기기

이메일 주소는 공개되지 않습니다.