3

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.

2 Answers 2

2

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

Comments

2

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']

Comments

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.