使用python读取xml元素

时间:2018-11-10 14:52:57

标签: python xml

我有一个xml文件。我想在文件中搜索一个特定的词,如果找到它,我想复制该词所在的所有xml元素。

例如:

 <Actions>
    <ActionGroup enabled="yes" name="viewsGroup" isExclusive="yes"/>
    <ExtAction iconSet=""  toolTip="" name="f5-script" text="f5-script"/>
</Actions> 

我正在寻找单词“ ExtAction”,由于它位于Actions元素内,因此我想复制所有元素。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我通常使用ElementTree进行此类工作,因为对我来说,这似乎是最直观的。我相信这是标准库的一部分,因此无需安装任何东西

作为一种更通用的方法,可以将整个.xml文件解析为字典的字典,然后,您可以根据需要对其进行索引。可以这样做(我只是在本地制作了一个.xml文件的副本,并出于演示目的将其称为“ test.xml”。当然,如果选择此解决方案,请将其更改为与您的文件相对应):

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

tags = [child.tag for child in root]
file_contents = {}
for tag in tags:
    for p in tree.iter(tag=tag):
        file_contents[tag] = dict(p.items())

如果打印文件内容,您将得到:

“ {'ActionGroup':{'enabled':'yes','name':'viewsGroup','isExclusive':'yes'},'ExtAction':{'iconSet':'','toolTip' :'','name':'f5-script','text':'f5-script'}}“”

由此可以轻松地索引出您需要的信息。例如,如果要从ExtAction标记中获取名称值,则只需执行以下操作:

print(file_contents['ExtAction']['name'])  # or save this as a variable if you need it

希望这会有所帮助!