How to Get Child Elements in XML Using Python

There are occasions when you are working with XML files and you need to navigate and access the child elements within the XML structure. Python’s libraries make it quite easy and straightforward. This tutorial will guide you on how to get child elements in an XML file using Python.

Step 1: Importing Necessary Libraries

Firstly, you need to import the xml.etree.ElementTree module, which comes built-in with Python and provides methods to parse and build XML data. You don’t need to install anything.

Step 2: Parsing the XML File

Next, you will parse the XML you want to extract data from using the ET.parse() function. You have to provide the name of the xml file as the argument. For instance, ‘sample.xml’ will be parsed as follows:

Step 3: Accessing Child Elements

You’re on to the primary stage. Here, you can access the child elements by using the getchildren() method or simply using a for loop like this:

This will print the name and attributes of the child elements in the root element. You can substitute the print function with your desired operation or task.

Files Used in this Tutorial

XML File: sample.xml

<data>
    <country name="Liechtenstein">
        <rank>68</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
    </country>
    <country name="Singapore">
        <rank>41</rank>
        <year>2001</year>
        <gdppc>59900</gdppc>
    </country>
</data>

Full Code

Output

country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}

Conclusion

And that’s it! In this tutorial, you learned how to get child elements in XML using Python. This can be quite handy when dealing with large XML files where manual viewing is not feasible.

Note that the xml.etree.ElementTree module can also be used to create or write an XML file, and modify or delete data in existing XML files. If you find it challenging to understand Python’s inbuilt module to parse XML, there are also other powerful libraries like lxml, and Beautiful Soup.