2017-09-15 21 views
0
from lxml import etree 
from xml.etree import cElementTree as ET 
tree = ET.parse(r"D:\General\Python_Preference_validation\sample.xml") 
root = tree.getroot() 
root[0][1].text 

這裏獲取元素的值是XML文件:試圖通過與ElementTree的功能指數LXML沒有輸出

<?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> 
</data> 

我期待着得到輸出爲2008,但是當我運行該腳本,它不提供任何輸出或抱怨任何語法錯誤。粘貼代碼和XML以及

+0

XML被驗證是存在於一些目錄的位置。 – Yogi

+0

本地測試,它工作正常。如果你嘗試這樣做會發生什麼:'for root in root:print r'? – floatingpurr

+0

@floatingpurr for循環給我<元素「國家」在0x000001CDAF0A9048> <元素「國家」在0x000001CDAF54F8B8> <元素「國家」在0x000001CDAF557B38>我想全年元素的對比 – Yogi

回答

0

也許你剛剛到print

print root[0][1].text # output '2008' 
+0

多虧了它簡單的平面列表.. .. :) – Yogi

+0

不客氣,隨時標記爲接受,如果它有幫助。 – floatingpurr