2016-08-05 16 views
0

私はPython DocsでXMLファイルからタグ名を取得する方法を研究していますが、それほど成功していません。以下のXMLファイルを使用して、国名タグと関連するすべての子タグを取得できます。誰がこれがどのように行われたか知っていますか?Pythonを使って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> 
</data> 
+0

ルック。 – Keozon

答えて

1

要素ツリーのiterparse()を使用し、タグとテキストのペアのネストされたリストを作成することを検討してください。条件付きifロジックは、グループの国のアイテムに一緒に使用し、テキストのない要素を除外され、その後、replace()は、改行や複数の空白を一掃するために使用されるiterparse()をピックアップ:BeautifulSoup4ライブラリに

import xml.etree.ElementTree as et 

data = [] 
for (ev, el) in et.iterparse(path): 
    inner = [] 

    if el.tag == 'country':   
     for name, value in el.items(): 
      inner.append([el.tag+'-'+name, str(value).replace('\n','').replace(' ','')]) 
     for i in el: 
      if str(i.text) != 'None': 
       inner.append([i.tag, str(i.text).replace('\n','').replace(' ','')]) 

      for name, value in i.items(): 
       inner.append([i.tag+'-'+name, str(value).replace('\n','').replace(' ','')]) 
     data.append(inner) 

print(data) 
# [[['country-name', 'Liechtenstein'], ['rank', '1'], ['year', '2008'], ['gdppc', '141100'], 
# ['neighbor-name', 'Austria'], ['neighbor-direction', 'E'], 
# ['neighbor-name', 'Switzerland'], ['neighbor-direction', 'W']] 
# [['country-name', 'Singapore'], ['rank', '4'], ['year', '2011'], ['gdppc', '59900'], 
# ['neighbor-name', 'Malaysia'], ['neighbor-direction', 'N']] 
# [['country-name', 'Panama'], ['rank', '68'], ['year', '2011'], ['gdppc', '13600'], 
# ['neighbor-name', 'CostaRica'], ['neighbor-direction', 'W'], 
# ['neighbor-name', 'Colombia'], ['neighbor-direction', 'E']]] 
-1

Pythonの組み込みXML機能を調べて、文書を再帰的にトラバースし、セット内のすべてのタグを収集します。

関連する問題