Python学习-ElementTree 方法读取XML

要想解析XML需分两步:

第一步: 加载XML文件
    1) 加载指定字符串
    2) 加载指定文件

第二步: 获取节点的方法
    1) 通过 getiterator
    2) 通过 getchildren
    3) find 方法
    4) findall 方法


#coding=GBK
from xml.etree import ElementTree as ET

def print_node(node):
    print "=============================================="  
    print "node.attrib:%s" % node.attrib  
    print "node.tag:%s" % node.tag  
    print "node.text:%s" % node.text  
    if node.attrib.has_key("name"):  
        print "node.attrib['rank']:%s" % node.attrib['name']  

if __name__ == '__main__':
#第一步:  加载XML文件
    #1.从变量读取,参数为XML段,返回的是一个根Element对象
    root = ET.fromstring(open("test.xml").read())
    print (type(root)) #打印结果: 
    
    #2.从xml文件中读取,用getroot获取根节点,根节点也是Element对象
    tree = ET.parse(r'test.xml')
    root2 = tree.getroot()
    print (type(root2)) #打印结果: 
    
#第二步: 获取节点的方法
    # 1.通过getiterator   
    print('1.通过getiterator  ')
    first_node = root.getiterator("country")  
    for node in first_node:  
        print_node(node)  
    #获取指定某个节点(这里是"country") 个数
    print first_node.__len__()
    
    # 2.通过 getchildren获取指定某个节点的子节点
    print ('2.通过 getchildren获取指定某个节点的子节点')
    first_node_child = first_node[0].getchildren()[0]  
    print_node(first_node_child)
    print first_node[0].getchildren()[1], first_node[0].getchildren()[1].tag
          
    # 3.find方法 ,返回第一个找到的节点 
    print ('3.find方法,返回第一个找到的节点  ')
    node_find = root.find('country2')  
    print node_find, node_find.attrib, '=='
    print_node(node_find)  
      
    # 4.findall方法  
    print ('4.findall方法,返回一个所有找到的节点的元组   ')
    node_findall = root.findall("country/rank")  
    print node_findall


test.xml:



    
        1
        2008
        141100
        
        
    
    
        4
        2011
        59900
        
    
    
        68
        2011
        13600
        
        
    
    
        234
        2016
        346344
        
        
    
    


你可能感兴趣的:(python)