How to Read XML File in Python?

  • Python
  • 2 mins read

Here I am giving an example to how to read an XML file in Python. The following is the data structure of XML file, which I am using in this example:

<?xml version="1.0"?>
<ROWSET>
<ROW>
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
<MGR>7902</MGR>
<HIREDATE>17-DEC-80</HIREDATE>
<SAL>800</SAL>
<COMM>217.5</COMM>
<DEPTNO>20</DEPTNO>
</ROW>

You can download the full sample of this XML file by clicking on the following link Download XML File.

Read and Print Values From an XML File in Python Example

In the following Python program, it will read the XML file contents as shown above using the ElementTree library and will print the values on the screen.

import xml.etree.ElementTree as ET

tree = ET.parse('emp_record.xml')
root = tree.getroot()
mgr = ''
for e in root.findall('ROW'):
    empno = e.find('EMPNO').text
    ename = e.find('ENAME').text
    job = e.find('JOB').text
    # check for MGR field because it is missing for one record in XML
    if not (e.find('MGR') is None):
        mgr = e.find('MGR').text
    hdate = e.find('HIREDATE').text
    sal = e.find('SAL').text
    comm = e.find('COMM').text
    deptno = e.find('DEPTNO').text
    print(ename, empno, job, mgr, hdate, sal, comm, deptno)

Output

SMITH 7369 CLERK 7902 17-DEC-80 800 217.5 20
ALLEN 7499 SALESMAN 7698 20-FEB-81 1600 188 30
WARD 7521 SALESMAN 7698 22-FEB-81 1250 188 30
JONES 7566 MANAGER 7839 02-APR-81 2975 217.5 20
MARTIN 7654 SALESMAN 7698 28-SEP-81 1250 188 30
BLAKE 7698 MANAGER 7839 01-MAY-81 2850 188 30
CLARK 7782 MANAGER 7839 09-JUN-81 2450 175 10
SCOTT 7788 ANALYST 7566 19-APR-87 3000 217.5 20
KING 7839 PRESIDENT 7566 17-NOV-81 5000 175 10
TURNER 7844 SALESMAN 7698 08-SEP-81 1500 188 30
ADAMS 7876 CLERK 7788 23-MAY-87 1100 217.5 20
JAMES 7900 CLERK 7698 03-DEC-81 950 188 30
FORD 7902 ANALYST 7566 03-DEC-81 3000 217.5 20
MILLER 7934 CLERK 7782 23-JAN-82 1300 175 10

See also: