XMLファイルがあり、特定の文字列を探しています。その文字列が見つかったら、その親の名前を返したい。ここに私のXMLは次のとおりです。Python - XMLで特定の文字列が見つかったときに親の名前を返す方法
<context>
<name>AccuCapacityApp</name>
<message>
<source>Capacity</source>
<translation type="unfinished">Kapazität</translation>
</message>
<message>
<source>Charge Level</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Sel (Yes)</source>
<translation type="unfinished">Sel (Ja)</translation>
</message>
<message>
<source>Esc (No)</source>
<translation type="unfinished">Esc (Nein)</translation>
</message>
</context>
私は「ソース」と「メイン」として「AccuCapacityApp」と「未完」と復帰「容量」を検索したいです。
私はこれを試してみましたが、それは何も出力しません:
import xml.etree.ElementTree as ET
file = "work.xml"
tree = ET.parse(file)
for elem in tree.findall('context/message'):
found = elem.get('unfinished')
print(found.attrib)
印刷元は正確に機能します。 print( "Source:"、tree.find( './ name')) 'を印刷しようとしましたが、" None "と表示されます。私はあなたがここに与えたリンクを訪問しました。私はどの答えに従うか分からない。 'tree.find( '.// b/..')'も "None"を返します。最も投票された回答にはforループがもう1つ含まれています。これにどのように含めるべきですか? – John
私はそれをどうやってそれを理解しました。 parent_map = dict((c、p)for tree.getiterator()in c for p) 'とマッピングした後、parent_map [message] .find( 'name')。 。助けてくれてありがとう。 – John