Reputation: 81
I'm trying to get values of in to a list. I need to get a list with this values new_values = ['a','b'] using xpath
import xml.etree.ElementTree as ET
parse = ET.parse('xml.xml')
[ record.find('events').text for record in parse.findall('.configuration/system/') ]
xml.xml file
<rpc-reply>
<configuration>
<system>
<preference>
<events>a</events>
<events>b</events>
</preference>
</system>
</configuration>
</rpc-reply>
The output of my python code is a list only with one value - ['a'], but i need a list with a and b.
Upvotes: 3
Views: 2666
Reputation: 92854
Optimized to a single .findall()
call:
import xml.etree.ElementTree as ET
root = ET.parse('input.xml').getroot()
events = [e.text for e in root.findall('configuration/system//events')]
print(events)
configuration/system//events
- relative xpath to events
element(s)The output:
['a', 'b']
Upvotes: 2
Reputation: 82765
You are pretty close. You just need to use findall('events')
and iterate it to get all values.
Ex:
import xml.etree.ElementTree as ET
parse = ET.parse('xml.xml')
print([ events.text for record in parse.findall('.configuration/system/') for events in record.findall('events')])
Output:
['a', 'b']
Upvotes: 2