2012-02-19 115 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」標籤之間的所有內容。現在我想搜索它們下面的兩個標記(「a」和「l」),如果指定,並打印它們。通過列表中提供像這樣的標籤:

switches = ["a", "l"] 

不過,我試圖找到的ElementTree的東西,讓我從列表中搜索這些標籤和打印出來分開,然而,「 find'和'findall'命令,當我嘗試給它提供「開關」列表時,返回「不可用的類型列表」。

那麼,我將如何搜索標籤列表併爲每個標籤打印文本?

謝謝你的時間。

最好的問候, Ĵ

回答

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 
相關問題