python 解析xml文件

一简单的xml文件

xml version="1.0" encoding="UTF-8"?>

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

运行结果

python 解析xml文件_第1张图片

你可能感兴趣的:(python 解析xml文件)