1

Given the following xml example, how can I print both the Actor name and their location?

I would like for the output to be:

John Cleese Ohio Eric Idle Colorado

<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
        <Location>
            <State>
                <name>Ohio</>
            </State>
        </Location>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
        <Location>
            <State>
                <name>Colorado</>
            </State>
        </Location>
    </actor>
</actors>

I tried the below code but it only prints the actor's names and does not print the states names

import xml.etree.ElementTree as ET

tree = ET.parse('Actors.xml')
root = tree.getroot()

root = fromstring(xml_text)
for actor in root.findall('{http://people.example.com}actor'):
    name = actor.find('{http://people.example.com}name')
    print(name.text)
    for state in actor.findall('{http://characters.example.com}state'):
        print(' |-->', state.text)
1

1 Answer 1

1

Try it this way:

actors = root.findall('.//{*}actor')
for actor in actors:
    name = actor.find('./{*}name')
    location = actor.find('./{*}Location//{*}name')
    print(name.text, location.text)

Output:

John Cleese Ohio
Eric Idle Colorado
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Jack, just out of curiosity, what if there is more than one state, how could I grab both? <actor> <name>Eric Idle</name> <fictional:character>Sir Robin</fictional:character> <fictional:character>Gunther</fictional:character> <fictional:character>Commander Clement</fictional:character> <Location> <state> <name>Colorado</> </state> <state> <name>Texas</> </state> </Location> </actor>
@Clyde I believe it's doable, but may be too long for a comment. It's probably best to just post it as a separate question.

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.