python xml.etree.ElementTree遍历xml所有节点实例详解

yipeiwu_com7年前Python基础

python xml.etree.ElementTree遍历xml所有节点

XML文件内容:

<students> 
  <student name='刘备' sex='男' age='35'/> 
  <student name='吕布' sex='男' age='38'/> 
  <student name='貂蝉' sex='女' age='22'/> 
</students> 

代码:



#-*- coding: UTF-8 -*-  
# 从文件中读取数据 
import xml.etree.ElementTree as ET 
 
#全局唯一标识 
unique_id = 1 
 
#遍历所有的节点 
def walkData(root_node, level, result_list): 
  global unique_id 
  temp_list =[unique_id, level, root_node.tag, root_node.attrib] 
  result_list.append(temp_list) 
  unique_id += 1 
   
  #遍历每个子节点 
  children_node = root_node.getchildren() 
  if len(children_node) == 0: 
    return 
  for child in children_node: 
    walkData(child, level + 1, result_list) 
  return 
 
#获得原始数据 
#out: 
#[ 
#  #ID, Level, Attr Map 
#  [1, 1, {'ID':1, 'Name':'test1'}], 
#  [2, 1, {'ID':1, 'Name':'test2'}], 
#] 
def getXmlData(file_name): 
  level = 1 #节点的深度从1开始 
  result_list = [] 
  root = ET.parse(file_name).getroot() 
  walkData(root, level, result_list) 
 
  return result_list 
 
if __name__ == '__main__': 
  file_name = 'test.xml' 
  R = getXmlData(file_name) 
  for x in R: 
    print x 
  pass 

输出结果:



[1, 1, 'students', {}] 
[2, 2, 'student', {'age': '35', 'name': u'\u5218\u5907', 'sex': u'\u7537'}] 
[3, 2, 'student', {'age': '38', 'name': u'\u5415\u5e03', 'sex': u'\u7537'}] 
[4, 2, 'student', {'age': '22', 'name': u'\u8c82\u8749', 'sex': u'\u5973'}] 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

详解Python判定IP地址合法性的三种方法

IP合法性校验是开发中非常常用的,看起来很简单的判断,作用确很大,写起来比较容易出错,今天我们来总结一下,看一下3种常用的IP地址合法性校验的方法。 IPv4的ip地址格式:(1~2...

python 3.6.4 安装配置方法图文教程

python 3.6.4 安装配置方法图文教程

今天补一下关于如何安装Python的操作步骤: 我的系统是我win系统 64 位 1.第一步先去python的官方网站下载python的安装包:地址 根据自己的系统选择对应的...

Python redis操作实例分析【连接、管道、发布和订阅等】

本文实例讲述了Python redis操作。分享给大家供大家参考,具体如下: 一、redis redis是一个key-value存储系统。和Memcached类似,它支持存储的value...

python的set处理二维数组转一维数组的方法示例

for splitValue in set(dataset[:, featureIndex].tolist()): 首先set是一个无序,无重复的数据结构,所以很多时候使用它来进行去重;...

使用Python来开发微信功能

使用Python来开发微信功能

在移动社交时代,微信已经成为我们生活不可或缺的一部分。2017年的《微信数据报告》中显示:每天有380亿条消息从微信上发出,其中6亿条是语音消息,有350万个活跃的公众账号,并存在着8亿...