使用xml.dom.minidom创建xml

from xml.dom.minidom import Document

doc = Document()

persons = doc.createElement('persons')#根节点
doc.appendChild(persons)#将根节点添加到xml对象

person1 = doc.createElement('person')#创建person节点
person1Name = doc.createElement('name')#创建姓名节点
person1NameText = doc.createTextNode('zhangsan')#创建文本节点
person1Name.appendChild(person1NameText)#将文本节点添加到姓名节点内

#first person
person1Age = doc.createElement('age')
person1AgeText = doc.createTextNode('20')
person1Age.appendChild(person1AgeText)
person1.appendChild(person1Name)#将姓名节点添加到person节点内
person1.appendChild(person1Age)

#second person
person2Age = doc.createElement('age')
person2AgeText = doc.createTextNode('20')
person2Age.appendChild(person1AgeText)
person2.appendChild(person1Name)
person2.appendChild(person1Age)

persons.appendChild(person1)#add the first person into root element将person节点添加到根节点persos根节点内部
persons.appendChild(person2)#add the second person into root element

xml = doc.toprettyxml(indent='    ')#xml object into string
fh = open('01.xml', 'w')
fh.write(xml)

总结:和php操作dom的方式基本一样。

原文地址:https://www.cnblogs.com/mtima/p/3051181.html