2016-05-19 4 views
1

私はPythonとXMlの初心者です。私はXMLファイルを解析し、その値とその値の合計を見つけようとしています。私はコードと以下のデータを含めました。数字のためのPythonでのXMLの解析

import xml.etree.ElementTree as ET 
data=''' 
<place> 
    <note>Test data</note> 
    <hospitals> 
    <doctor> 
     <name>John</name> 
     <count>97</count> 
    </doctor> 
    <doctor> 
     <name>Sam</name> 
     <count>97</count> 
    </doctor> 
    <doctor> 
     <name>Luke</name> 
     <count>90</count> 
    </doctor> 
    <doctor> 
     <name>Mark</name> 
     <count>90</count> 
    </doctor> 
    </hospitals> 
</place> ''' 

tree=ET.fromstring (data) 
for lines in tree.findall('place/hospitals/doctor'): 
    print lines.get('count'), lines.text 

上記のコードを実行すると、出力が得られません。 は、それから私はにコードを変更:

tree=ET.fromstring (data) 
print 'count:',tree.find('count').text 

、出力は次のようになります。

Traceback (most recent call last): 
    File "test2.py", line 26, in <module> 
    print 'count:',tree.find('count').text 
AttributeError: 'NoneType' object has no attribute 'text' 

すべてのヘルプは、みんなに感謝しています。 ありがとうございます

答えて

0

Element.findall()は、現在の要素の直接の子であるタグを持つ要素のみを検索します。 ElementTreeのドキュメントはhereです。 コード例もそうです。

今のところ、これを試してみてください:上記のコードは、単にカウントを印刷し

for line in tree.findall('./hospitals/doctor/count'): print line.text

。それらを合計するコードを記述する必要があります。

+0

それがうまくいった!どうもありがとうございました :) – sooraj

関連する問題