Clyde
Clyde

Reputation: 143

Using XPath in ElementTree to find Nested Elements

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)

Upvotes: 1

Views: 359

Answers (1)

Jack Fleeting
Jack Fleeting

Reputation: 24930

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

Upvotes: 1

Related Questions