Python xml.etree.ElementTree traversal XML All node instances detailed _python

Source: Internet
Author: User

Python xml.etree.ElementTree traversal of all XML nodes

XML file Contents:

<students> 
  <student name= ' Liu Bei ' sex= ' man ' age= '/> <student ' lv bu ' name= ' sex= ' 
  man ' 
  <student name= ' Diao Chan ' sex= ' female ' age= '/> 
</students> 

Code:



#-*-coding:utf-8-*-  
# Read data from File 
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 to Child in 
  Children_node: 
    Walkdata (Child, Level + 1, result_list) 
  return 
 
#获得原始数据 
#out: 
#[ 
#  #ID, level, Attr map< c23/>#  [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 

Output results:



[1, 1, ' Students ', {}] 
[2, 2, ' student ', {' age ': '], ' name ': U ' \u5218\u5907 ', ' Sex ': U ' \u7537 '}] 
[3, 2, ' student ', {' age ': '], ' name ': U ' \u5415\u5e03 ', ' Sex ': U ' \u7537 '}] 
[4, 2, ' student ', {' age ': ' n ', ' name ': U ' \u8c82\u8749 ', ' Sex ': U ' \u5973 '}] 

Thank you for reading, I hope to help you, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.