Skip to content
Advertisement

How do I extract value of XML attribute in Python?

I need to extract the value of an attribute in an XML document using Python.

For example, If I have an XML document like this:

JavaScript

How would I be able get the text ‘smallHuman’ or ‘largeHuman’ to store in a variable?

Edit: I’m very new to Python and may require a lot of assistance.

This is what I’ve tried so far:

JavaScript

Due to the way this script will be used, I cannot hard-code the XML into the .py file.

Advertisement

Answer

Using ElementTree you can use find method & attrib .

Example:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement