I want to create a list with all the id's/attribute values of an element based on conditions in subelements. When making the loop, the output is a list with the attribute value (id) for every subelement. Here, I just need the attribute value (id) in the element 'playevent' once for every parent element.
Here is a part of the XML file:
</file>
<ALL_INSTANCES>
<playerevent id="1">
<starttime></starttime>
<endtime></endtime>
<player>/player>
<quarter></quarter>
<result>
<kind number="1"></kind>
<means number="1"></means>
</result>
</playerevent>
<playevent id="2" type=">
<starttime></starttime>
<endtime></endtime>
<zone></zone>
<label>
<group></group>
<text>/text>
</label>
<label>
<group></group>
<text></text>
</label>
<label>
<text></text>
</label>
<label>
<group></group>
<text></text>
</label>
<score team=""></score>
<score team=""></score>
<label>
<text></text>
</label>
<team></team>
</playevent>
Edit: This is another element with subelement 'playevent'
<playevent id="10" type="">
<starttime></starttime>
<endtime></endtime>
<zone></zone>
<label>
<group></group>
<text></text>
</label>
<label>
<group></group>
<text></text>
</label>
<label>
<group>/group>
<text></text>
</label>
<label>
<text></text>
</label>
<score team=""></score>
<score team=""></score>
<previousevent>
</previousevent>
<label>
<text></text>
</label>
<label>
<text></text>
</label>
<team></team>
</playevent>
I have tried multiple solutions like creating a functions that give the unique values in a list. I have tried.findall() to change the loop. But all the outcomes are the same.
for subelem1 in elem:
for subelem2 in subelem1:
for subelem2 in subelem1.findall('previousevent'):
if subelem2.tag == 'previousevent':
list = subelem1.get('id')
print(list)
Current output: 2 2 2 2 2 2 2 2 2 2 2 2
Expected output: 2
You can just use a "predicate" expression [previousevent]
with findall
:
for playevent in tree.findall('.//playevent[previousevent]'):
print(playevent.get('id'))
So
import xml.etree.ElementTree as ET
xml = '''
<ALL_INSTANCES>
<playevent id="1">
<foo>..</foo>
<bar>..</bar>
</playevent>
<playevent id="2">
<foo>..</foo>
<bar>..</bar>
<previousevent></previousevent>
<baz>..</baz>
</playevent>
<playevent id="3">
<foo>..</foo>
<bar>..</bar>
</playevent>
<playevent id="4">
<foo>..</foo>
<bar>..</bar>
<previousevent></previousevent>
<baz>..</baz>
</playevent>
</ALL_INSTANCES>
'''
tree = ET.fromstring(xml)
for playevent in tree.findall('.//playevent[previousevent]'):
print(playevent.get('id'))
outputs
2
4
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.