导航:首页 > 编程语言 > python怎么建xml

python怎么建xml

发布时间:2025-03-04 03:58:07

Ⅰ 如何用Python创建生成xml文档文件的方法

1、内存数据产生

2、产生xml内存对象(也就是DOM树)

3、产生根对象

4、往根对象里加数据

5、把xml内存对象写到文件

下面是一个创建xml文档的简单实例:

importxml.dom.minidom#在内存中创建一个空的文档doc=xml.dom.minidom.Document()
#创建一个根节点Managers对象root=doc.createElement('Managers')
#设置根节点的属性root.setAttribute('company','xx科技')
root.setAttribute('address','科技软件园')
#将根节点添加到文档对象中doc.appendChild(root)

managerList=[{'name':'joy','age':27,'sex':'女'},
{'name':'tom','age':30,'sex':'男'},
{'name':'ruby','age':29,'sex':'女'}
]foriinmanagerList:
nodeManager=doc.createElement('Manager')
nodeName=doc.createElement('name')
#给叶子节点name设置一个文本节点,用于显示文本内容
nodeName.appendChild(doc.createTextNode(str(i['name'])))

nodeAge=doc.createElement("age")
nodeAge.appendChild(doc.createTextNode(str(i["age"])))

nodeSex=doc.createElement("sex")
nodeSex.appendChild(doc.createTextNode(str(i["sex"])))

#将各叶子节点添加到父节点Manager中,
#最后将Manager添加到根节点Managers中
nodeManager.appendChild(nodeName)
nodeManager.appendChild(nodeAge)
nodeManager.appendChild(nodeSex)
root.appendChild(nodeManager)#开始写xml文档fp=open('c:\wcx\Manager.xml','w')
doc.writexml(fp,indent=' ',addindent=' ',newl=' ',encoding="utf-8")

执行结果:

<?xmlversion="1.0"encoding="utf-8"?>
<Managersaddress="科技软件园"company="xx科技">
<Manager>
<name>joy</name>
<age>27</age>
<sex>女</sex>
</Manager>
<Manager>
<name>tom</name>
<age>30</age>
<sex>男</sex>
</Manager>
<Manager>
<name>ruby</name>
<age>29</age>
<sex>女</sex>
</Manager>
</Managers>

6.用Python自带的写xml文档的API去写,比较方便,后期容易维护。如果直接用打开文件的方式,一行一行的去写,比较费时,也难以维护。

阅读全文

与python怎么建xml相关的资料

热点内容
压缩机每次启动12分钟就停 浏览:729
creo复制曲面命令 浏览:959
程序员恋上女硕士 浏览:668
ansys的get命令 浏览:987
国外dns苹果服务器地址 浏览:430
国家职业技术资格证书程序员 浏览:652
奇瑞租车app是什么 浏览:98
系统源码安装说明 浏览:420
命令行加壳 浏览:96
解压时显示防失效视频已加密 浏览:295
苹果短信加密发送 浏览:446
天翼私有云服务器租用 浏览:733
贵州云服务器属于哪个上市公司 浏览:58
编程联动教程 浏览:481
小天才app怎么升级v242 浏览:545
简单手工解压玩具制作大全 浏览:928
免费编程电子书 浏览:870
想玩游戏什么app最合适 浏览:560
安卓手机如何用airportspro 浏览:449
怎么清理idea编译缓存 浏览:952