python use dom to write xml file

#encoding:utf-8
'''
    write xml in dom style 
'''

from xml.dom.minidom import Document

doc = Document() # new a DOM object

words = doc.createElement('words') # new a root element
words.setAttribute('xmlns:xsi',"http://www.w3.org/2001/XMLSchema-instance")#设置命名空间
doc.appendChild(words)

elem = doc.createElement('word')
elem.setAttribute('name','english')
words.appendChild(elem)

# or you could do like the following:
#elem = doc.createElement('word') #words.appendChild(elem) #text = doc.createElement('name') #text_node = doc.createTextNode('english') #text.appendChild(text_node) #elem.appendChild(text) print doc.toxml()
原文地址:https://www.cnblogs.com/slider/p/3183515.html