2017-05-01 18 views
1

のサンプルXMLから取得要素 - XMLパイソン

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

以下のPythonのElementTree

import xml.etree.ElementTree as ET 
tree = ET.parse('test.xml') 


for elem in tree.iter(tag='name'): 
    print (elem.tag) 

ディスプレイを3名の要素を使用。どのようにして特定のテキストを持つ1つの名前要素<name>Panama</name>を検索することができますか?

for elem in tree.iter(tag="name='panama'"):はまた

答えて

1
import xml.etree.ElementTree as ET 

tree = ET.parse('test.xml') 
countries = tree.findall("country") 
for country in countries: 
    name = country.find("name") 
    if name.text == "Panama": 
     print(name.text) 

を働いていない、あなたのXMLの形式が正しくないことに注意してください。 test.xmlの19行目に>の代わりに]があります

1

xpathlxmlに使用するとよいでしょう。 text()を使用すると、素早く要素のコンテンツとして「パナマ」を見つけることができます。これを済ませたら、同じ国の近隣の情報項目にナビゲートすることができます。

>>> from lxml import etree 
>>> tree = etree.parse('test.xml') 
>>> tree.xpath('.//name/text()') 
['Liechtenstein', 'Singapore', 'Panama'] 
>>> for item in tree.xpath('.//name/text()'): 
...  if item == 'Panama': 
...   for cousins in item.getparent().getparent().getchildren(): 
...    cousins.text 
...    
'Panama' 
'68' 
'2011' 
'13600' 
関連する問題