编程语言
首页 > 编程语言> > python 解析xml文件

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])

运行结果

标签:xml,namelist,python,tree,lists,alister,datalist,解析
来源: https://www.cnblogs.com/caozewen/p/12164091.html