Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse xml xpath into list python

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.

like image 949
Goroshek Avatar asked Mar 07 '26 01:03

Goroshek


2 Answers

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']
like image 96
Rakesh Avatar answered Mar 09 '26 15:03

Rakesh


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']
like image 36
RomanPerekhrest Avatar answered Mar 09 '26 15:03

RomanPerekhrest