2012-02-19 82 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 
相关问题