Python解析XML文件
XML与JSON的互相转化详见:XML模块
https://www.cnblogs.com/shengyang17/p/8606223.html
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
# coding=utf-8
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml") #open
root = tree.getroot() #f.seek(0) <Element 'data' at 0x027EAAE0>
print(root.tag) #data 根节点 for child in root:
print('-------------',child.tag,child.attrib) #------------- country {'name': 'Liechtenstein'}
for i in child:
print(i.tag, i.text) ##获取xml: <rank updated="yes">2</rank> <year>2008</year>
''' ##rank 2 year 2008
------------- country {'name': 'Liechtenstein'}
rank 2
year 2008
gdppc 141100
neighbor None
neighbor None
------------- country {'name': 'Singapore'}
rank 5
year 2011
gdppc 59900
neighbor None
------------- country {'name': 'Panama'}
rank 69
year 2011
gdppc 13600
neighbor None
neighbor None
''' for node in root.iter('year'): ##只遍历year节点
print(node.tag, node.text)
'''
year 2008
year 2011
year 2011
'''
event.xml
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Events>
<Event xmlns1='http://schemas.microsoft.com/win/2004/08/events/event'>
<System>
<Provider Name='Microsoft-Windows-Security-SPP' Guid='{E23B3380-C8C9-472C-F28DFEA0F156}' EventSourceName='Software Protection Platform Server'></Provider>
<EventID Qualifiers='16384'>902</EventID>
<Version>0</Version>
<Level>0</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x80000000000</Keywords>
<TimeCreated SystemTime='2018-12-25T09:08:59.00000000000Z'/>
<EventRecordID>8634</EventRecordID>
<Correlation/>
<Execution ProcessID='0' ThreadID='0'/>
<Channel>Application</Channel>
<Computer>WIN-CANDBPBBOCN</Computer>
<Security/>
</System>
<EventData>
<Date>6.1.7601.17514</Date>
</EventData>
<RenderingInfo Culture='zh-CN'>
<Message>软件保护服务已启动。6.1.7601.17514</Message>
<Level>信息</Level>
<Task></Task>
<Opcode></Opcode>
<Channel></Channel>
<Provider>Microsoft-Window-Security-SPP</Provider>
<keywords>
<keyword>经典</keyword>
</keywords>
</RenderingInfo>
</Event> <Event xmlns1='http://schemas.microsoft.com/win/2004/08/events/event'>
<System>
<Provider Name='Microsoft-Windows-Security-SPP' Guid='{E23B3380-C8C9-472C-F28DFEA0F156}' EventSourceName='Software Protection Platform Server'></Provider>
<EventID Qualifiers='16384'>902</EventID>
<Version>0</Version>
<Level>0</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x80000000000</Keywords>
<TimeCreated SystemTime='2018-12-25T09:08:59.00000000000Z'/>
<EventRecordID>8634</EventRecordID>
<Correlation/>
<Execution ProcessID='0' ThreadID='0'/>
<Channel>Application</Channel>
<Computer>WIN-CANDBPBBOCN</Computer>
<Security/>
</System>
<EventData>
<Date>6.1.7601.17514</Date>
</EventData>
<RenderingInfo Culture='zh-CN'>
<Message>软件保护服务已启动。6.1.7601.17514</Message>
<Level>信息</Level>
<Task></Task>
<Opcode></Opcode>
<Channel></Channel>
<Provider>Microsoft-Window-Security-SPP</Provider>
<keywords>
<keyword>经典</keyword>
</keywords>
</RenderingInfo>
</Event> <Event xmlns1='http://schemas.microsoft.com/win/2004/08/events/event'>
<System>
<Provider Name='Microsoft-Windows-Security-SPP' Guid='{E23B3380-C8C9-472C-F28DFEA0F156}' EventSourceName='Software Protection Platform Server'></Provider>
<EventID Qualifiers='16384'>902</EventID>
<Version>0</Version>
<Level>0</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x80000000000</Keywords>
<TimeCreated SystemTime='2018-12-25T09:08:59.00000000000Z'/>
<EventRecordID>8634</EventRecordID>
<Correlation/>
<Execution ProcessID='0' ThreadID='0'/>
<Channel>Application</Channel>
<Computer>WIN-CANDBPBBOCN</Computer>
<Security/>
</System>
<EventData>
<Date>6.1.7601.17514</Date>
</EventData>
<RenderingInfo Culture='zh-CN'>
<Message>软件保护服务已启动。6.1.7601.17514</Message>
<Level>信息</Level>
<Task></Task>
<Opcode></Opcode>
<Channel></Channel>
<Provider>Microsoft-Window-Security-SPP</Provider>
<keywords>
<keyword>经典</keyword>
</keywords>
</RenderingInfo>
</Event> <Event xmlns1='http://schemas.microsoft.com/win/2004/08/events/event'>
<System>
<Provider Name='Microsoft-Windows-Security-SPP' Guid='{E23B3380-C8C9-472C-F28DFEA0F156}' EventSourceName='Software Protection Platform Server'></Provider>
<EventID Qualifiers='16384'>902</EventID>
<Version>0</Version>
<Level>0</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x80000000000</Keywords>
<TimeCreated SystemTime='2018-12-25T09:08:59.00000000000Z'/>
<EventRecordID>8634</EventRecordID>
<Correlation/>
<Execution ProcessID='0' ThreadID='0'/>
<Channel>Application</Channel>
<Computer>WIN-CANDBPBBOCN</Computer>
<Security/>
</System>
<EventData>
<Date>6.1.7601.17514</Date>
</EventData>
<RenderingInfo Culture='zh-CN'>
<Message>软件保护服务已启动。6.1.7601.17514</Message>
<Level>信息</Level>
<Task></Task>
<Opcode></Opcode>
<Channel></Channel>
<Provider>Microsoft-Window-Security-SPP</Provider>
<keywords>
<keyword>经典</keyword>
</keywords>
</RenderingInfo>
</Event> </Events>
import xml.etree.ElementTree as ET def es(mvalue):
pass def packNodes(nodes,m):
'''
去除空字典方法
if len(nodes) < 0 or nodes.attrib == None or nodes.text == None:
return
'''
if len(nodes) < 0:
return
tag = nodes.tag ##所有的{key: value}key值
text = nodes.text ##所有的value值
m[tag] = {} ## m = {}空字典,把key值添加到新字典中;比如:{'Events': {}} {'Event': {}}, m的value作为{}空字典
m[tag].update(nodes.attrib) #nodes.attrib是打印出 把=两边的作为{key: value }字典的形式--作为m字典的value
#print(m) #{'Events': {}} {'Event': {'xmlns1': 'http://schemas.microsoft.com/win/2004/08/events/event'}}... if text != None:
if text.strip() != "":
m[tag]["value"] = text #去除空值和空格
for node in nodes: #nodes一开始是作为根节点
packNodes(node,m[tag]) ##递归调用 def main(): # 创建文档树
tree = ET.ElementTree(file="event.xml")
# 获取根节点
root = tree.getroot()
print(root)#<Element 'Events' at 0x01EAAB40>
list = []
for r in root:
m = {}
packNodes(root,m) #
list.append(m)
# root.attrib--->字典
# root.tag --->字符串
# root.text --->字符串
# 元素封装到map中
'''
封装单个数组
m = {}
packNodes(root,m)
'''
print(list)
# es(m) if __name__ == '__main__':
main()
结果如下:
[{'Events':
{'Event': {'xmlns1': 'http://schemas.microsoft.com/win/2004/08/events/event',
'System':
{'Provider': {'Name': 'Microsoft-Windows-Security-SPP', 'Guid': '{E23B3380-C8C9-472C-F28DFEA0F156}', 'EventSourceName': 'Software ProtectionPlatform Server'},
'EventID': {'Qualifiers': '', 'value': ''},
'Version': {'value': ''}, 'Level': {'value': ''},
'Task': {'value': ''},
'Opcode': {'value': ''},
'Keywords': {'value': '0x80000000000'},
'TimeCreated': {'SystemTime': '2018-12-25T09:08:59.00000000000Z'},
'EventRecordID': {'value': ''},
'Correlation': {},
'Execution': {'ProcessID': '', 'ThreadID': ''},
'Channel': {'value': 'Application'},
'Computer': {'value': 'WIN-CANDBPBBOCN'},
'Security': {}},
'EventData': {'Date': {'value': '6.1.7601.17514'}},
'RenderingInfo': {'Culture': 'zh-CN', 'Message': {'value': '软件保护服务已启动。6.1.7601.17514'}, 'Level':{'value': '信息'}, 'Task': {}, 'Opcode': {}, 'Channel': {}, 'Provider': {'value': 'Microsoft-Window-Security-SPP'}, 'keywords': {'keyword': {'value': '经典'}}}
}}},
{'Events':
{'Event': {'xmlns1': 'http://schemas.microsoft.com/win/2004/08/events/event', 'System': {'Provider': {'Name': 'Microsoft-Windows-Security-SPP',
'Guid': '{E23B3380-C8C9-472C-F28DFEA0F156}', 'EventSourceName': 'Software Protec
tion Platform Server'}, 'EventID': {'Qualifiers': '16384', 'value': '902'}, 'Ver
sion': {'value': '0'}, 'Level': {'value': '0'}, 'Task': {'value': '0'}, 'Opcode'
: {'value': ''}, 'Keywords': {'value': '0x80000000000'}, 'TimeCreated': {'Syste
mTime': '2018-12-25T09:08:59.00000000000Z'}, 'EventRecordID': {'value': '8634'},
'Correlation': {}, 'Execution': {'ProcessID': '', 'ThreadID': ''}, 'Channel':
{'value': 'Application'}, 'Computer': {'value': 'WIN-CANDBPBBOCN'}, 'Security':
{}}, 'EventData': {'Date': {'value': '6.1.7601.17514'}}, 'RenderingInfo': {'Cul
ture': 'zh-CN', 'Message': {'value': '软件保护服务已启动。6.1.7601.17514'}, 'Lev
el': {'value': '信息'}, 'Task': {}, 'Opcode': {}, 'Channel': {}, 'Provider': {'v
alue': 'Microsoft-Window-Security-SPP'}, 'keywords': {'keyword': {'value': '经典
'}}}}}},
...]
Python解析XML文件的更多相关文章
- python 解析xml 文件: Element Tree 方式
环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...
- python 解析xml 文件: DOM 方式
环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...
- python 解析xml 文件: SAX方式
环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...
- 遍历文件 创建XML对象 方法 python解析XML文件 提取坐标计存入文件
XML文件??? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 里面的标签都是可以随心所欲的按照他的命名规则来定义的,文件名为roi.xm ...
- Python 解析 XML 文件生成 HTML
XML文件result.xml,内容如下: <ccm> <metric> <complexity>1</complexity> <unit> ...
- 【TensorFlow】Python解析xml文件
最近在项目中使用TensorFlow训练目标检测模型,在制作自己的数据集时使用了labelimg软件对图片进行标注,产生了VOC格式的数据,但标注生成的xml文件标签值难免会产生个别错误造成程序无法跑 ...
- Python解析xml文件遇到的编码解析的问题
使用python对xml文件进行解析的时候,假设xml文件的头文件是utf-8格式的编码,那么解析是ok的,但假设是其它格式将会出现例如以下异常: xml.parsers.expat.ExpatErr ...
- [转载] python 解析xml 文件: SAX方式
环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...
- python解析xml文件时使用ElementTree和cElementTree的不同点;iter
在python中,解析xml文件时,会选用ElementTree或者cElementTree,那么两者有什么不同呢? 1.cElementTree速度上要比ElementTree快,比较cElemen ...
- python 解析 XML文件
如下使用xml.etree.ElementTree模块来解析XML文件.ElementTree模块中提供了两个类用来完成这个目的: ElementTree表示整个XML文件(一个树形结构) Eleme ...
随机推荐
- 第一周java学习总结
学号 20175206 <Java程序设计>第一周学习总结 教材学习内容总结 第一章是关于JAVA入门的注意事项: 第一章主要按照顺序讲了JAVA的地位,诞生,特点,JDK的安装,一些ja ...
- Presto服务发现(Discovery Service)
Presto 集群配置不管是coordinator还是worker配置项中都有一项discovery.uri,这个是一个比较核心的东西,简单来说就是服务发现的地址. coordinator和worke ...
- MySQL实战45讲学习笔记:索引(第五讲)
一.需要回表的案例 在下面表T中,执行下面语句,需要执行几次树的搜索操作?会扫描多少行? select * from T where k between 3 and 5 1.初始化语句 mysql&g ...
- 《Java》第八周学习总结
第八周学习内容:课本第15章节的内容泛型与集合框架 主要内容有 -泛型-链表-堆栈-散列映射-树集-树映射 重点和难点-重点:泛型和集合的使用码云:https://gitee.com/ShengHu ...
- iptables 防火墙日常
. 检查机目标机器 httpd 服务/etc/init.d/httpd status ========================================================= ...
- 文件共享服务器share
文件共享服务器:(类似于FTP服务器) 1.创建共享:文件夹右键属性--共享--开启共享--设置共享名--设置共享权限(建议设置为everyone完全控制,然后具体的权限需求在ntfs权限中设置即可) ...
- BUAA-OO-表达式解析与求导
BUAA-OO-表达式解析与求导 解析 按照常规,解析这一部分我们分为词法分析与语法分析.当然由于待解析的字符串较简单,词法分析器和语法分析器不必单独实现. 词法分析器 按照常规,我们先手写一个词法分 ...
- Leetcode-1.两数之和
题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数 ...
- 20175315 《Java程序设计》第6周学习总结
20175215 <Java程序设计>第6周学习总结 教材学习内容总结 第七章主要讲的是内部类,匿名类,异常类等等. 内部类:Java支持在一个类中定义另一个类,称作内部类,包含内部类的类 ...
- 3D Slicer中文教程(八)—导出STL文件
一.STL文件简介 STL(立体平版印刷术的缩写)是由3D Systems创建的立体平版印刷CAD软件原生的文件格式STL有“标准三角语言”和“标准镶嵌语言”等几个事后回溯.这种文件格式是由许多其他软 ...