2017-09-05 8 views
3

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) 

答えて

1

あなたはtree.findall('context/message')を使用して、すべてのmessageのノードを反復処理しているが、あなたはtranslationノードを(彼らはtype属性を保持する)必要があります。これはあなたのコードにsubsituteとして動作します:

for message in tree.iterfind('.//translation[@type="unfinished"]/..'): 
    print(message.attrib) 

それはundefinedに等しい属性typeと子translationをcaontaining messageノードを反復処理します。詳細については、XPathをPythonのドキュメントで読んでください。より効率的なiterfindを使用しました。

次に、あなたがsourceを抽出するためにmessageを使用する必要があります何をしたい達成するために:

for message in tree.iterfind('.//translation[@type="unfinished"]/..'): 
    print("Source: ", message.find('source').text) 

あなたがmessageの親を取得する必要がありますnameタグを取得するために。それについてはthis SE questionを参照してください。または、そのタグをtreetree.find('./name'))から取得するだけです。

幸運。

+0

印刷元は正確に機能します。 print( "Source:"、tree.find( './ name')) 'を印刷しようとしましたが、" None "と表示されます。私はあなたがここに与えたリンクを訪問しました。私はどの答えに従うか分からない。 'tree.find( '.// b/..')'も "None"を返します。最も投票された回答にはforループがもう1つ含まれています。これにどのように含めるべきですか? – John

+1

私はそれをどうやってそれを理解しました。 parent_map = dict((c、p)for tree.getiterator()in c for p) 'とマッピングした後、parent_map [message] .find( 'name')。 。助けてくれてありがとう。 – John

関連する問題