简体   繁体   中英

Read an xml element using python

I have an xml file. 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.

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. How can I do it?

I usually use ElementTree for this kind of job, as it seems the most intuitive to me. 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. 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):

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'}}"

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:

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

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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