python 解析xml文件
一简单的xml文件
<?xml version="1.0" encoding="UTF-8"?> <!-- This is TableName --> <tables> <table> <name name = "mydb" field = "asd"> </name> <field name1 = "mydb" field1 = "eas"> </field> <neighbor name2="mydb" field2="xxx"> </neighbor> <neighbor name3="mydb" field3="asdf"> </neighbor> </table> </tables>
python解析文件
# -*- coding=utf-8 -*- import xml.etree.ElementTree as ET tree = ET.ElementTree() # 实例化 tree.parse("./test.xml") root = tree.getroot() lists = {} for child in root: for sub in child: lists.update(sub.attrib) # 合并字典,为了防止因相同键名,而使字典的值被覆盖掉,所以在写xml时,键名都是区分开的 alister = [] namelist = [] datalist = [] for i in lists.values(): alister.append(i) namelist = alister[::2] # 获取列表的奇数项,即获得表名 datalist = alister[1::2] # 获取列表的偶数项,即获得字段名 for i in range(len(namelist)): print(namelist[i], datalist[i])
运行结果
相关推荐
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
XGQ 2020-07-04
Andrewjdw 2020-05-29
Yakamoz 2020-05-26
行吟阁 2020-05-18
88491874 2020-04-30
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16