【发布时间】:2012-03-10 09:41:10
【问题描述】:
我有一个需要解析的 xml 文件。如下:它被称为“fttk.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 中找到一些东西,可以让我从列表中搜索这些标签并分别打印出来,但是,ElementTree 或 Element 的“find”和“findall”命令返回当我尝试将“开关”列表提供给它时,“uhashable 类型列表”。
那么,我将如何搜索标签列表并为每个标签打印出文本?
感谢您的宝贵时间。
最好的问候, J
【问题讨论】:
标签: xml list python-3.x elementtree