Using Element Tree to parse XML (Python)

Viewed 37

I'm learning how to use ElementTree and I having some trouble parsing the XML as shown below. I ultimately would like to create a dictionary where the keys are the function id's and the values are a list of the callee id's (Ex. {'1': [20,22]}, {'3': [10,30,20,92]}) but I'm having trouble figuring out how to iterate through each function and access the id and callee attributes. I've been trying to use findall() but I've been unsuccessful so I was wondering if I could get some help. Thanks!

<?xml version="1.0" encoding="utf-8"?>
<myXML>
    <version>2</version>
    <functions>
        <function>
            <id>1</id>
            <callee>20</callee>
            <callee>22</callee>
        </function>
        <function>
            <id>3</id>
            <callee>10</callee>
            <callee>30</callee>
            <callee>20</callee>
            <callee>92</callee>
        </function>
    </functions>
</myXML>
1 Answers

Try something like this:

import xml.etree.ElementTree as ET
calls = """[your xml above]"""
doc = ET.fromstring(calls)

calls_dict = {}
funcs = doc.findall('.//function')
for func in funcs:
    id = func.find('./id').text
    callees = [call.text for call in func.findall('.//callee')]
    calls_dict[id]=callees
for a,b in calls_dict.items():
    print(a,b)

Output:

1 ['20', '22']
3 ['10', '30', '20', '92']
Related