user3848394
user3848394

Reputation: 67

Parsing Xml with element tree in Python, same tag name

I'm using python to parse a XML file but I have a problem. I'm sure there is a way to solve it but I'm new on python and parsing xml...

So here a example of xml :

<TeamData Ref = "1">
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
</TeamData>
<TeamData Ref = "2">
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
    <Goal></Goal>
</TeamData>

I want to store my element goal in two part in function of the team ref... How would I do that ? Because I tried :

for iterators in child.iter("TeamData"):
                something_to_store(iterators.tag)

But I have the list of all the 8 goals without difference in function of the teamdata ref !

Upvotes: 1

Views: 3527

Answers (1)

sundar nataraj
sundar nataraj

Reputation: 8702

a.xml

<?xml version="1.0"?>
<data>

<TeamData Ref = "1">
    <Goal>a</Goal>
    <Goal>b</Goal>
    <Goal>c</Goal>
    <Goal>d</Goal>
</TeamData>

<TeamData Ref = "2">
    <Goal>e</Goal>
    <Goal>f</Goal>
    <Goal>g</Goal>
    <Goal>h</Goal>
</TeamData>
    </data>

for each teamdata you need to iterate again to get Goals. so create dictonary with ref name as key and goals as values

import xml.etree.ElementTree as ET
tree = ET.parse('a.xml')
root = tree.getroot()
print root
dic={}
for i in root.iter('TeamData'):
    dic[i.attrib['Ref']]=[j.text for j in i]
print dic
#output {'1': ['a', 'b', 'c', 'd'], '2': ['e', 'f', 'g', 'h']}

Upvotes: 1

Related Questions