Python XML Parser - ElementTree With Examples

Python XML parser provides us an easy way to read the XML file and extract useful data. Today we will look into python ElementTree XML API and learn how to use it to parse XML file as well as modify and create XML documents.

Python XML Parser – Python ElementTree

Python ElementTree is one of the most efficient APIs to extract, parse and transform XML data using Python programming language. In this post, we will have good look at how to create, read, parse and update XML data in files and programmatically.

Let’s get started with Python XML parser examples using ElementTree.

Python ElementTree examples

We will start with a very simple example to create an XML file programmatically and then, we will move to more complex files.

Creating XML file

In this example, we will create a new XML file with an element and a sub-element. Let’s get started straight away:

Once we run this script, a new file will be created in the same directory with file named as test.xml with following contents:

There are two things to notice here:

  • While writing the file, we used wb mode instead of w as we need to write the file in binary mode.
  • The child user tag is a self-closing tag as we haven’t put any sub-elements in it.

Adding values to XML elements

Let’s improve the program by adding values to the XML elements:

Once we run this script, we will see that new elements are added added with values. Here are the content of the file:

This is perfectly valid XML and all tags are closed. Please note that I formatted the XML myself as the API writes the complete XML in a single fine which is kind a bit, incompleteness!

Now, let’s start with editing files.

Editing XML data

We will use the same XML file we showed above. We just added some more data into it as:

Let’s try and update salaries of each user:

It is worth noticing that if you try to update an elements value to an integer, it won’t work. You will have to assign a String, like:

instead of doing:

Python XML Parser Example

This time, let’s try to parse the XML data present in the file and print the data:

When we run above script, below image shows the output produced.

python-elementtree-values

In this post, we studied how to extract, parse, and transform XML files. ElementTree is one of the most efficient APIs to do these tasks. I would suggest you try some more examples of XML parsing and modifying different values in XML files.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: