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)) #打印結果: <class 'xml.etree.ElementTree.Element'>
    
    #2.從xml文件中讀取,用getroot獲取根節點,根節點也是Element對象
    tree = ET.parse(r'test.xml')
    root2 = tree.getroot()
    print (type(root2)) #打印結果: <class 'xml.etree.ElementTree.Element'>
    
#第二步: 獲取節點的方法
    # 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:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
    <country2 name="Test">
        <rank>234</rank>
        <year>2016</year>
        <gdppc>346344</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country2>
    
</data>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章