In my testing work, I have to read and parse xml a lot, using Python. This post documents my usage of xml.etree.ElementTree package of Python, to Read and parse the information I need.
First of all, let’s look at a typical xml file: test.xml under current directory.
<xml><status>1</status><cmd>SETNETWORK</cmd><data><value><configuration type=”wlan” allocation=”dhcp” ssid=”shVLr1H5UTPkQYWhz’dSHIiuopg” auth=”OPEN” encryption=”NONE”/></value></data></xml>
We begin with import the ElementTree pacage and read the file.
from xml.etree import ElementTree as ET
xml = ET.parse('test.xml')
root = xml.getroot()
The parse() method just read the file in as a xml.etree.ElementTree.ElementTree object, and the getroot() method makes sure that you are at the root element of the XML tree.
You could also make a string into a xml object. The following code shows that and also shows how to read a file into a string using Python.
file_string = open('./test.xml').read()
root = ET.fromstring(file_string)
The next thing we need to do is to find the element we need, and read some attributes from it.
config = root.find('data').find('value').find('configuration')
attributes = config.attrib
# the output should be 'dhcp'
See, as simple as using the find() method to get the accurate element, and attrib variable to get all the attributes of a element. If there are more than one element, you could use findall() functions.