python etree 操作xml

2017-01-10 10:04:51来源:oschina作者:shower1人点击

第七城市


### python etree 操作xml```
from xml.etree import ElementTree as ET
class CreateXML(object):
""" 创建xml文件 """def createxml(self,):
""" 创建xml文件 """
root = ET.ElementTree() # 实例化xml数对象
RootList = ET.Element('Root',{}) # 创建根节点
root._setroot(RootList) # 设置根节点
del_root = ET.ElementTree()# 实例化xml数对象
DelRootList = ET.Element('Root', {})# 创建根节点
del_root._setroot(DelRootList)# 设置根节点
m_list = [{'name':'zhangsa','age':'100'},{'name':'32434','age':'30'}]
for k in m_list:
AuList = ET.SubElement(RootList,'AuList')
for key,value in k.items():
keylist = ET.SubElement(AuList,key)# 设置属性值
keylist.text = value# 设置 value值
# print ET.parse(root)
m_list = [{'name': 'asdfasdf', 'age': '100'}, {'name': '3asdfasdf4', 'age': '30'}]
for k in m_list:
AuList = ET.SubElement(DelRootList, 'AuList')
for key, value in k.items():
keylist = ET.SubElement(AuList, key)# 设置属性值
keylist.text = value# 设置 value值
print root.write('./mm.xml',encoding='utf-8',xml_declaration=True) # 生成 xml 文件
print del_root.write('./mm1.xml',encoding='utf-8',xml_declaration=True) # 生成 xml 文件def parasexml(self):
""" 解析xml """
xml_str = """

BT1234
T

POST_POLICY_ADD-ExcuteSuccess,3/763iserror;[2353B692-F9D1-401E-B0F4-E75BCF944A41]:不存在此航线;[5C8BDF6F-C7EA-4798-8FD4-E40E73E9684D]:不存在此航线;[243F5FC8-C273-4ADF-812A-9AD6819A5140]:不存在此航线;;

回调地址

"""
root = ET.fromstring(xml_str)
for child in root:
print child.tag, child.textif __name__ == '__main__':
c_xml = CreateXML().createxml()
```
第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台