1

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 !

1 Answer 1

1

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']}
Sign up to request clarification or add additional context in comments.

1 Comment

what if there is a subelement between <Goal>e</Goal> and <Goal>f</Goal>? This parser seems to cannot extract text in a subelement. Please, how to also extract text from a subelement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.