1

I'm trying to select a nested element based on the value of an attribute

from xml.etree import ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
    <Report>
        <h1>
            <h2>
                <Element name='Bob' age='32' title='President'></Element>
                <Element name='Sue' age='25' title='Vice-President'></Element>
                <Element name='Mary' age='44' title='Secretary'></Element>
            </h2>
        </h1>
    </Report>'''

root = ET.fromstring(xml)

element = root.findall("//*[@title='President']")

But I get the following error for the element variable assignment

SyntaxError: cannot use absolute path on element

How can I pull the attribute data for the President element only?

2 Answers 2

1

You were very close :-)

The below works - look at the dot in the xpath..

xml = '''<?xml version="1.0" encoding="UTF-8"?>
    <Report>
        <h1>
            <h2>
                <Element name='Bob' age='32' title='President'></Element>
                <Element name='Sue' age='25' title='Vice-President'></Element>
                <Element name='Mary' age='44' title='Secretary'></Element>
            </h2>
        </h1>
    </Report>'''

root = ET.fromstring(xml)
elements = root.findall(".//*[@title='President']")
print(elements)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @balderman. I get the element assignment that way, but I can't access the attribute values that way. This does not work: print(element.attrib["name"], element.attrib["age"], element.attrib["title"]). Is there another way to pull those attribute values?
Did you try and print the attrib ?
I needed to loop through element like @AudioBaton does. Thanks for your help.
0

is this what you're looking for?

from xml.etree import ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
    <Report>
        <h1>
            <h2>
                <Element name='Bob' age='32' title='President'></Element>
                <Element name='Sue' age='25' title='Vice-President'></Element>
                <Element name='Mary' age='44' title='Secretary'></Element>
            </h2>
        </h1>
    </Report>'''


root = ET.fromstring(xml)
elements = root.findall(".//*[@title='President']")
for i in elements:
    print(i.attrib['name'], i.attrib['age'], i.attrib['title'])

1 Comment

I was missing the dot in the findall and didn't know I needed to loop through elements. Thanks! This works for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.