2016-10-05 9 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

print(data)は私に文字列を返します。また、三重引用符は、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')) 
関連する問題