0

I am finding difficult parsing this XML:

<menuItems>
    <menuItem>
        <text>Auto 4-spd, 6 cyl, 3.8 L, 3.8N</text>
        <value>14864</value>
    </menuItem>
    <menuItem>
        <text>Auto 4-spd, 8 cyl, 4.6 L</text>
        <value>14866</value>
    </menuItem>
    <menuItem>
        <text>Man 5-spd, 6 cyl, 3.8 L</text>
        <value>14865</value>
    </menuItem>
</menuItems>

I am doing it like this:

list = []
response = et.XML(urllib.request.urlopen(url).read())
for i, child in enumerate(response):
    for subchild in child:
        lista.append({subchild.tag : subchild.text})

So when I print the list, item by item, I receive this:

{'text': 'Auto 4-spd, 6 cyl, 3.8 L, 3.8N'}
{'value': '14864'}
{'text': 'Auto 4-spd, 8 cyl, 4.6 L'}
{'value': '14866'}
{'text': 'Man 5-spd, 6 cyl, 3.8 L'}
{'value': '14865'}

Instead of that, I would like to receive something like this:

{'Auto 4-spd, 6 cyl, 3.8 L, 3.8N': '14864'}
{'Auto 4-spd, 8 cyl, 4.6 L': '14866'}
{'Man 5-spd, 6 cyl, 3.8 L': '14865'}

1 Answer 1

1
lista = []
response = et.XML(xml)
for i, child in enumerate(response):
    text = child.find('text').text
    value = child.find('value').text
    lista.append({text: value})
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work. When I print an item of the list I get: {<Element 'text' at 0x7f39bdc9dd68>: <Element 'value' at 0x7f39bdc9dea8>}
It seems like you are missing the .text

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.