Python is an object-oriented programming language ideally designed for rapid prototyping of complex applications. Like Perl, Python source code is also available under the GNU General Public License (GPL).

In this article we will see how to How to Parse XML file in python, lets say we have a xml file (employee.xml) in the same directory as the python script.

employee.xml
<employees>
	<employee id="1">
		<name>tbNext 1</name>
		<dept type="development" />
	</employee>
	<employee id="2">
		<name>tbNext 2</name>
		<dept type="development" />
	</employee>
	<employee id="3">
		<name>tbNext 3</name>
		<dept type="development" />
	</employee>
</employees>

1) Print root children's attributes value

import xml.etree.ElementTree as ET
tree = ET.parse('employee.xml')
root = tree.getroot()

for child in root:
	print(child.tag, child.attrib)

Output: Output will be something like this:

('employee', {'id': '1'})
('employee', {'id': '2'})
('employee', {'id': '3'})


2) Getting specific element using indexes:

import xml.etree.ElementTree as ET
tree = ET.parse('employee.xml')
root = tree.getroot()

print root[1][0].text

Output: Output will be something like this:

tbNext 2


3) Print attribute values and text between tags:

import xml.etree.ElementTree as ET
tree = ET.parse('employee.xml')
root = tree.getroot()

for employee in root.findall('employee'):
	name = employee.find('name').text
	id = employee.get('id')
	print(name, id)

Output: Output will be something like this:

('tbNext 1', '1')
('tbNext 2', '2')
('tbNext 3', '3')


4) Print single tag attribute values:

import xml.etree.ElementTree as ET
tree = ET.parse('employee.xml')
root = tree.getroot()

for dept in root.iter('dept'):
	print(dept.attrib).get('type')

Output: Output will be something like this:

development
development
development


In this article we have seen, How to Parse XML in python, read node attributes values and single node values in python. In upcoming articles we will see more complex usecases and tricks of python.
  • By Techburps.com
  • Sep 30, 2017
  • Python