If you have followed this blog for a while, you may remember that we’ve covered several XML parsing libraries that are included with Python. In this article, we’ll be continuing that series by taking a quick look at the ElementTree library. You will learn how to create an XML file, edit XML and parse the XML. For comparison’s sake, we’ll use the same XML we used in the previous minidom article to illustrate the differences between using minidom and ElementTree. Here is the original XML:
1181251680 040000008200E000 1181572063 1800 Bring pizza home
Now let’s dig into the Python!
How to Create XML with ElementTree
Creating XML with ElementTree is very simple. In this section, we will attempt to create the XML above with Python. Here’s the code:
import xml.etree.ElementTree as xml #---------------------------------------------------------------------- def createXML(filename): """ Create an example XML file """ root = xml.Element("zAppointments") appt = xml.Element("appointment") root.append(appt) # add appointment children begin = xml.SubElement(appt, "begin") begin.text = "1181251680" uid = xml.SubElement(appt, "uid") uid.text = "040000008200E000" alarmTime = xml.SubElement(appt, "alarmTime") alarmTime.text = "1181572063" state = xml.SubElement(appt, "state") location = xml.SubElement(appt, "location") duration = xml.SubElement(appt, "duration") duration.text = "1800" subject = xml.SubElement(appt, "subject") tree = xml.ElementTree(root) with open(filename, "w") as fh: tree.write(fh) #---------------------------------------------------------------------- if __name__ == "__main__": createXML("appt.xml")
If you run this code, you should get something like the following (probably all on one line):
1181251680 040000008200E000 1181572063 1800
This is pretty close to the original and is certainly valid XML, but it’s not quite the same. However, it’s close enough. Let’s take a moment to review the code and make sure we understand it. First we create the root element by using ElementTree’s Element function. Then we create an appointment element and append it to the root. Next we create SubElements by passing the appointment Element object (appt) to SubElement along with a name, like “begin”. Then for each SubElement, we set its text property to give it a value. At the end of the script, we create an ElementTree and use it to write the XML out to a file.
What’s annoying is that it write out the XML all on one line instead of in a nice readable format (i.e. “pretty print”). There’s a recipe on Effbot, but there doesn’t appear to be a way to do it internally. You may also want to take a look at some of the other solutions on StackOverflow. It should be noted that lxml supports “pretty print” out of the box.
Now we’re ready to learn how to edit the file!
How to Edit XML with ElementTree
Editing XML with ElementTree is also easy. To make things a little more interesting though, we’ll add another appointment block to the XML:
1181251680 040000008200E000 1181572063 1800 Bring pizza home 1181253977 sdlkjlkadhdakhdfd 1181588888 TX Dallas 1800 Bring pizza home
Now let’s write some code to change each of the begin tag’s values from seconds since the epoch to something a little more readable. We’ll use Python’s time module to facilitate this:
import time import xml.etree.cElementTree as ET #---------------------------------------------------------------------- def editXML(filename): """ Edit an example XML file """ tree = ET.ElementTree(file=filename) root = tree.getroot() for begin_time in root.iter("begin"): begin_time.text = time.ctime(int(begin_time.text)) tree = ET.ElementTree(root) with open("updated.xml", "w") as f: tree.write(f) #---------------------------------------------------------------------- if __name__ == "__main__": editXML("original_appt.xml")
Here we create an ElementTree object (tree) and we extract the root from it. Then we use ElementTree’s iter() method to find all the tags that are labeled “begin”. Note that the iter() method was added in Python 2.7. In our for loop, we set each item’s text property to a more human readable time format via time.ctime(). You’ll note that we had to convert the string to an integer when passing it to ctime. The output should look something like the following:
Thu Jun 07 16:28:00 2007 040000008200E000 1181572063 1800 Bring pizza home Thu Jun 07 17:06:17 2007 sdlkjlkadhdakhdfd 1181588888 TX Dallas 1800 Bring pizza home
You can also use ElementTree’s find() or findall() methods to get search for specific tags in your XML. The find() method will just find the first instance whereas the findall() will find all the tags with the specified label. These are helpful for editing purposes or for parsing, which is our next topic!
How to Parse XML with ElementTree
Now we get to learn how to do some basic parsing with ElementTree. First we’ll read through the code and then we’ll go through bit by bit so we can understand it. Note that this code is based around the original example, but it should work on the second one as well.
import xml.etree.cElementTree as ET #---------------------------------------------------------------------- def parseXML(xml_file): """ Parse XML with ElementTree """ tree = ET.ElementTree(file=xml_file) print tree.getroot() root = tree.getroot() print "tag=%s, attrib=%s" % (root.tag, root.attrib) for child in root: print child.tag, child.attrib if child.tag == "appointment": for step_child in child: print step_child.tag # iterate over the entire tree print "-" * 40 print "Iterating using a tree iterator" print "-" * 40 iter_ = tree.getiterator() for elem in iter_: print elem.tag # get the information via the children! print "-" * 40 print "Iterating using getchildren()" print "-" * 40 appointments = root.getchildren() for appointment in appointments: appt_children = appointment.getchildren() for appt_child in appt_children: print "%s=%s" % (appt_child.tag, appt_child.text) #---------------------------------------------------------------------- if __name__ == "__main__": parseXML("appt.xml")
You may have already noticed this, but in this example and the last one, we’ve been importing cElementTree instead of the normal ElementTree. The main difference between the two is that cElementTree is C-based instead of Python-based, so it’s much faster. Anyway, once again we create an ElementTree object and extract the root from it. You’ll note that e print out the root and the root’s tag and attributes. Next we show several ways of iterating over the tags. The first loop just iterates over the XML child by child. This would only print out the top level child (appointment) though, so we added an if statement to check for that child and iterate over its children too.
Next we grab an iterator from the tree object itself and iterate over it that way. You get the same information, but without the extra steps in the first example. The third method uses the root’s getchildren() function. Here again we need an inner loop to grab all the children inside each appointment tag. The last example uses the root’s iter() method to just loop over any tags that match the string “begin”.
As mentioned in the last section, you could also use find() or findall() to help you find specific tags or sets of tags respectively. Also note that each Element object has a tag and a text property that you can use to acquire that exact information.
Wrapping Up
Now you know how to use ElementTree to create, edit and parse XML. You can add that information to your XML parsing toolkit and use it for fun or profit. You will find links to previous articles on some of the other XML parsing tools below as well as additional information about ElementTree itself.
Related Articles from Mouse Vs Python
Additional Reading
- Official Python documentation for ElementTree
- Effbot’s ElementTree Overview
- Processing XML in Python with elementree
- Dr Chuck’s Simple ElementTree Example
Download the Source
Can I as why you use this style,
appointments = root.getchildren()
for appointment in appointments:
appt_children = appointment.getchildren()
for appt_child in appt_children:
rather than this style ?
for appointment in root.getchildren():
for appt_child in appointment.getchildren():
According to Effbot, cElementTree should be 15-20 times faster: http://effbot.org/zone/celementtree.htm. Also according to this site, it’s also more memory efficient: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree/
I suppose I was just being pedantic…and I was trying to minimize my line widths to prevent my readers from having to scroll my code examples. In this case, it probably didn’t help much though.
Pingback: Visto nel Web – 77 | Ok, panico
ElementTree is an easy to use and understood with the XML where tag plays crucial roles to easy understanding.
Mike can you help me to add rss to my project ?
Currently
I am using perl script that is handled manually and I want the process
to be automated. I mean my project is python based, while the rss is
handled manually via perl. Can you re-write “buildpy” to produce atom or rss automatically ?
(https://)github(dot)com/wifiextender/blogfy
I’m not sure why disqus is removing comments with links and those
that are edited. Sorry for the duplicated questions in this thread.
the code to add another appointment block is missing
For those running Python3.4 who have the error: “TypeError: must be str, not bytes”, can solve that by adding “wb” as the file open mode. This will write the file out in binary mode.
Is there a way to print the whole xml ?I have tried so far:
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import tostring
etree = ET.parse(‘file.xml’)
text = tostring(etree)
print text
root = etree.getroot()
But, its not working.
When I try the “Edit XML” example and edit an XML element, instead of editing the value, it is edited to a self-closing tag. I was editing the ‘salary’ tag:
for salary in root.iter("salary"):
salary.text = 0.0
In the updated XML file, we have:
Before updating, value was:
10
Yeah, this is true. I don’t think ElementTree supports data types other than strings, so you would want to try to cast your input to a string before updating it.
Pingback: Python: Creating XML with lxml.objectify - The Mouse Vs. The Python