简体   繁体   English

使用 python 读取 xml 元素

[英]Read an xml element using python

I have an xml file.我有一个 xml 文件。 I want to search for a specific word in the file, and if i find it- i want to copy all of the xml element the word was in it.我想在文件中搜索一个特定的词,如果我找到它 - 我想复制这个词所在的所有 xml 元素。

for example:例如:

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

I am looking for the word :"ExtAction", and since it is inside the Actions element I want to copy all of it.我正在寻找单词 :"ExtAction",因为它在Actions元素中,所以我想复制所有它。 How can I do it?我该怎么做?

I usually use ElementTree for this kind of job, as it seems the most intuitive to me.我通常将 ElementTree 用于此类工作,因为它对我来说似乎是最直观的。 I believe this is part of the standard library, so no need to install anything我相信这是标准库的一部分,所以不需要安装任何东西

As a more general approach, the entire .xml file can be parsed as a dictionary of dictionaries, which you can then index accordingly if you so desired.作为一种更通用的方法,可以将整个 .xml 文件解析为字典字典,然后您可以根据需要对其进行相应的索引。 This can be done like this (I just made a copy of your .xml file locally and called it "test.xml" for demonstration purposes. Of course, change this to correspond to your file if you choose this solution):这可以像这样完成(我只是在本地复制了您的 .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())

If you print the file contents you will get:如果您打印文件内容,您将获得:

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

From this it is trivial to index out the bits of information you need.由此,索引出您需要的信息位是微不足道的。 For example, if you want to get the name value from the ExtAction tag, you would just do:例如,如果您想从 ExtAction 标记中获取 name 值,您只需执行以下操作:

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

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM