2012-02-19 7 views
2

解析する必要があるXMLファイルがあります。以下のとおりです: "fttk.xml"Python:XMLファイルで要素のリストを検索して印刷する方法

<root> 
    <ls> 
     this is the ls 
    <a> 
     this is the ls -a 
    </a> 
    <l> 
     this is the ls -l 
    </l> 
    </ls> 
    <dd> 
     this is the dd 
     <a> 
     this is the dd -a 
     </a> 
     <l> 
     this is the dd -l 
     </l> 
    </dd> 
</root> 

かなり単純です。 "ls"タグまたは "dd"タグのいずれかのテキストを印刷することができます。指定されていれば、その下のタグを印刷します。

これまでXMLで "ls"タグまたは "dd"タグを見つけ、タグ内のテキストを印刷することができました。私はこのコードでこれを行なった:

import xml.etree.ElementTree as ET 

command = "ls" 

fttkXML = ET.parse('fttk.xml') #parse the xml file into an elementtree 
findCommand = fttkXML.find(command) #find the command in the elementtree 
if findCommand != None: 
    print (findCommand.text) #prints that tag's text 

これで、私は "ls" ... "/ ls"タグの間のすべてを保存しました。今は指定されていれば、その下にある2つのフラグ( "a"と "l")を検索して印刷したいと思います。タグはそのようなリストで提供されています。しかし

switches = ["a", "l"] 

、私は私がリストからこれらのタグを検索して、しかし、それらを個別にプリントアウトすることができますElementTreeの中に何かを見つけることを試みてきました " ElementTreeまたはElementの 'find'と 'findall'コマンドは、 'switches'リストをフィードしようとすると "uhashable type list"を返します。

タグのリストを検索し、各タグにテキストを印刷するにはどうすればよいですか?

ありがとうございます。

よろしく、 Jタグの

答えて

2

することはでき​​:

import xml.etree.ElementTree as ET 

command = "ls" 
switches = ["a", "l"] 

fttkXML = ET.parse('fttk.xml') #parse the xml file into an elementtree 
findCommand = fttkXML.find(command) #find the command in the elementtree 

if findCommand != None: 
    print findCommand.text  #prints that tag's text 
    for sub in list(findCommand): # find all children of command. In older versions use findCommand.getchildren() 
     if sub.tag in switches: # If child in switches 
      print sub.text  # print child tag's text 
関連する問題