【Python】创建xml文档

时间:2023-03-08 23:21:33
【Python】创建xml文档
#练习:创建xml文档
import xml.dom.minidom
import codecs
#在内存中创建一个空的文档
doc = xml.dom.minidom.Document()
#创建一个根节点companys对象
root = doc.createElement('companys')
# 给根节点root添加属性
root.setAttribute('name', u'公司信息')
#将根节点添加到文档对象中
doc.appendChild(root)
# 给根节点添加一个叶子节点gloryroad
company = doc.createElement('gloryroad')
# 叶子节点下再嵌套叶子节点name
name = doc.createElement("Name")
# 给节点添加文本节点
name.appendChild(doc.createTextNode(u"光荣之路教育科技公司"))
#跟name同级的添加了一个CEO节点
ceo = doc.createElement('CEO')
ceo.appendChild(doc.createTextNode(u'吴总'))
# 将各叶子节点添加到父节点company中
company.appendChild(name)
company.appendChild(ceo)
# 然后将company添加到跟节点companys中
root.appendChild(company)
print doc.toxml()
#保存xml
fp = codecs.open('e:\\company.xml', 'w','utf-8')
doc.writexml(fp, indent='', addindent='\t', newl='\n', encoding="utf-8") #indent=根节点缩进 #addindent=子节点缩进
#newl=针对新行,指明换行方式 #encoding=指明所写xml文档的编码
fp.close()
#练习:自己创建一个xml文件,例如:刚才的database的配置文件
import xml.dom.minidom
import codecs
doc = xml.dom.minidom.Document()
root = doc.createElement("sqlserver")
root.setAttribute("type","get ip")
doc.appendChild(root)
ip = doc.createElement('ip')
host = doc.createElement("host")
host.appendChild(doc.createTextNode("10.60.6.6"))
username = doc.createElement("username")
username.appendChild(doc.createTextNode("wangjing"))
password = doc.createElement("password")
password.appendChild(doc.createTextNode("1111"))
ip.appendChild(host)
ip.appendChild(username)
ip.appendChild(password)
root.appendChild(ip)
print doc.toxml()