2016-10-05 134 views
0

我想解析一個xml數據以在Python 3中用ElementTree庫打印它的內容。但是當我打印lst時,它返回一個空列表。使用ElementTree庫解析XML

Error: Returning an empty array of list.

我嘗試:

import xml.etree.ElementTree as ET 
data = ''' 
    <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> 
    </data>''' 

tree = ET.fromstring(data) 
lst = tree.findall('data/country') 
print(lst) 
#for item in lst: 
# print('Country: ', item.get('name')) 

在此先感謝。

+1

Viraj Kaulkar:不知道它是否足夠好,但'lst = tree.findall('country')'似乎工作。 – martineau

+0

打印(數據)給我回串。而三重單引號用於在python 3中編寫多行字符串。 –

回答

1

樹已經引用根項目<data>,所以它不應該在你的路徑語句中。只要找到「國家」。

import xml.etree.ElementTree as ET 
data = ''' 
    <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> 
    </data>''' 

tree = ET.fromstring(data) 
lst = tree.findall('data/country') 
print(lst) 

# check position in tree 
print(tree.tag) 
print(tree.findall('country'))