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代码真的很爽

不知道怎么忽然想看这个,呵呵 小我的python的反shell的代码 #!/usr/bin/python # Python Connect-back Bac...

pandas修改DataFrame列名的实现方法

提出问题 存在一个名为dataset的DataFrame >>> dataset.columns Index(['age', 'job', 'marital',...

树莓派使用python-librtmp实现rtmp推流h264的方法

目的是能使用Python进行rtmp推流,方便在h264帧里加入弹幕等操作。 librtmp使用的是0.3.0,使用树莓派noir官方摄像头适配的。 通过wireshark抓ffmpeg...

python3中的md5加密实例

在python3的标准库中,已经移除了md5,而关于hash加密算法都放在hashlib这个标准库中,如SHA1、SHA224、SHA256、SHA384、SHA512和MD5算法等。...

python matplotlib画图库学习绘制常用的图

python matplotlib画图库学习绘制常用的图

本文实例为大家分享了python matplotlib绘制常用图的具体代码,供大家参考,具体内容如下 github地址 导入相关类 import numpy as np import...