Read An Xml Element Using Python
Solution 1:
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!
Post a Comment for "Read An Xml Element Using Python"