Processing XML in Python — ElementTree
Learn how you can parse, explore, modify and populate XML files with the Python ElementTree package, for loops and XPath expressions. As a data scientist, you’ll find that understanding XML is powerful for both web-scraping and general practice in parsing a structured document
Extensible Markup Language (XML) is a markup language which encodes documents by defining a set of rules in both machine-readable and human-readable format. Extended from SGML (Standard Generalized Markup Language), it lets us describe the structure of the document. In XML, we can define custom tags. We can also use XML as a standard format to exchange information.
- XML documents have sections, called elements, defined by a beginning and an ending tag. A tag is a markup construct that begins with < and ends with >. The characters between the start-tag and end-tag, if there are any, are the element’s content. Elements can contain markup, including other elements, which are called «child elements».
- The largest, top-level element is called the root, which contains all other elements.
- Attributes are name–value pair that exist within a start-tag or empty-element tag. An XML attribute can only have a single value and each attribute can appear at most once on each element.
Here’s a snapshot of movies.xml that we will be using for this tutorial:
DVD
PG
'Archaeologist and adventurer Indiana Jones
is hired by the U.S. government to find the Ark of the Covenant before the Nazis.'
DVD,Online
PG
None provided.
Blu-ray
PG
Marty McFly
dvd, digital
PG-13
Two mutants come to a private academy for their kind whose resident superhero team must oppose a terrorist organization with similar powers.
VHS
PG13
NA.
Online
R
WhAtEvER I Want.
DVD
R
"""""""""
DVD
PG13
Funny movie on funny guy
blue-ray
Unrated
psychopathic Bateman
Introduction to ElementTree
The XML tree structure makes navigation, modification, and removal relatively simple programmatically. Python has a built in library, ElementTree, that has functions to read and manipulate XMLs (and other similarly structured files).
First, import ElementTree . It’s a common practice to use the alias of ET :
import xml.etree.ElementTree as ET
Parsing XML Data
In the XML file provided, there is a basic collection of movies described. The only problem is the data is a mess! There have been a lot of different curators of this collection and everyone has their own way of entering data into the file. The main goal in this tutorial will be to read and understand the file with Python — then fix the problems.
First you need to read in the file with ElementTree .
tree = ET.parse('movies.xml')
root = tree.getroot()
Now that you have initialized the tree, you should look at the XML and print out values in order to understand how the tree is structured.
root.tag'collection'
At the top level, you see that this XML is rooted in the collection tag.
For Loops
You can easily iterate over subelements (commonly called “children”) in the root by using a simple “for” loop.
for child in root:
print(child.tag, child.attrib)genre
genre
genre
Now you know that the children of the root collection are all genre . To designate the genre, the XML uses the attribute category . There are Action, Thriller, and Comedy movies according the genre element.
Typically it is helpful to know all the elements in the entire tree. One useful function for doing that is root.iter() .
[elem.tag for elem in root.iter()]['collection',
'genre',
'decade',
'movie',
'format',
'year',
'rating',
'description',
'movie',
.
.
.
.
'movie',
'format',
'year',
'rating',
'description']
There is a helpful way to see the whole document. If you pass the root into the .tostring() method, you can return the whole document. Within ElementTree, this method takes a slightly strange form.
Since ElementTree is a powerful library that can interpret more than just XML, you must specify both the encoding and decoding of the document you are displaying as the string.
You can expand the use of the iter() function to help with finding particular elements of interest. root.iter() will list all subelements under the root that match the element specified. Here, you will list all attributes of the movie element in the tree:
for movie in root.iter('movie'):
print(movie.attrib)
XPath Expressions
Many times elements will not have attributes, they will only have text content. Using the attribute .text , you can print out this content.
Now, print out all the descriptions of the movies.
for description in root.iter('description'):
print(description.text)'Archaeologist and adventurer Indiana Jones is hired by the U.S. government to find the Ark of the Covenant before the Nazis.'None provided.
Marty McFly
Two mutants come to a private academy for their kind whose resident superhero team must oppose a terrorist organization with similar powers.
NA.
WhAtEvER I Want.
"""""""""
Funny movie about a funny guy
psychopathic Bateman
What a joke!
Emma Stone = Hester Prynne
Tim (Rudd) is a rising executive who “succeeds” in finding the perfect guest, IRS employee Barry (Carell), for his boss’ monthly event, a so-called “dinner for idiots,” which offers certain
advantages to the exec who shows up with the biggest buffoon.Who ya gonna call?
Robin Hood slaying
Printing out the XML is helpful, but XPath is a query language used to search through an XML quickly and easily. However, Understanding XPath is critically important to scanning and populating XMLs. ElementTree has a .findall() function that will traverse the immediate children of the referenced element.
Here, you will search the tree for movies that came out in 1992:
for movie in root.findall("./genre/decade/movie/[year='1992']"):
print(movie.attrib)
The function .findall() always begins at the element specified. This type of function is extremely powerful for a «find and replace». You can even search on attributes!
Now, print out only the movies that are available in multiple formats (an attribute).
for movie in root.findall("./genre/decade/movie/format/[@multiple='Yes']"):
print(movie.attrib)
Brainstorm why, in this case, the print statement returns the “Yes” values of multiple . Think about how the «for» loop is defined.
Tip: use ‘. ‘ inside of XPath to return the parent element of the current element.
for movie in root.findall("./genre/decade/movie/format[@multiple='Yes']. "):
print(movie.attrib)
Modifying an XML
Earlier, the movie titles were an absolute mess. Now, print them out again:
for movie in root.iter('movie'):
print(movie.attrib)
Fix the ‘2’ in Back 2 the Future. That should be a find and replace problem. Write code to find the title ‘Back 2 the Future’ and save it as a variable:
b2tf = root.find(«./genre/decade/movie[@title=’Back 2 the Future’]»)
print(b2tf)
Notice that using the .find() method returns an element of the tree. Much of the time, it is more useful to edit the content within an element.
Modify the title attribute of the Back 2 the Future element variable to read «Back to the Future». Then, print out the attributes of your variable to see your change. You can easily do this by accessing the attribute of an element and then assigning a new value to it:
b2tf.attrib[«title»] = «Back to the Future»
print(b2tf.attrib)
Write out your changes back to the XML so they are permanently fixed in the document. Print out your movie attributes again to make sure your changes worked. Use the .write() method to do this:
tree.write("movies.xml")tree = ET.parse('movies.xml')
root = tree.getroot()for movie in root.iter('movie'):
print(movie.attrib)
Fixing Attributes
The multiple attribute is incorrect in some places. Use ElementTree to fix the designator based on how many formats the movie comes in. First, print the format attribute and text to see which parts need to be fixed.
for form in root.findall("./genre/decade/movie/format"):
print(form.attrib, form.text) DVD
DVD,Online
Blu-ray
dvd, digital
VHS
Online
DVD
DVD
blue-ray
DVD,VHS
DVD
DVD,digital,Netflix
Online,VHS
Blu_Ray
There is some work that needs to be done on this tag.
You can use regex to find commas — that will tell whether the multiple attribute should be «Yes» or «No». Adding and modifying attributes can be done easily with the .set() method.
import refor form in root.findall("./genre/decade/movie/format"):
# Search for the commas in the format text
match = re.search(',',form.text)
if match:
form.set('multiple','Yes')
else:
form.set('multiple','No')# Write out the tree to the file again
tree.write("movies.xml")tree = ET.parse('movies.xml')
root = tree.getroot()for form in root.findall("./genre/decade/movie/format"):
print(form.attrib, form.text) DVD
DVD,Online
Blu-ray
dvd, digital
VHS
Online
DVD
DVD
blue-ray
DVD,VHS
DVD
DVD,digital,Netflix
Online,VHS
Blu_Ray
Moving Elements
Some of the data has been placed in the wrong decade. Use what you have learned about XML and ElementTree to find and fix the decade data errors.
It will be useful to print out both the decade tags and the year tags throughout the document.
for decade in root.findall("./genre/decade"):
print(decade.attrib)
for year in decade.findall("./movie/year"):
print(year.text)
1981
1984
1985
2000
1992
1992
1979
1986
2000
1966
2010
2011
1984
1991
The two years that are in the wrong decade are the movies from the 2000s. Figure out what those movies are, using an XPath expression.
for movie in root.findall("./genre/decade/movie/[year='2000']"):
print(movie.attrib)
You have to add a new decade tag, the 2000s, to the Action genre in order to move the X-Men data. The .SubElement() method can be used to add this tag to the end of the XML.
action = root.find("./genre[@category='Action']")
new_dec = ET.SubElement(action, 'decade')
new_dec.attrib["years"] = '2000s'
Now append the X-Men movie to the 2000s and remove it from the 1990s, using .append() and .remove() , respectively.
xmen = root.find("./genre/decade/movie[@title='X-Men']")
dec2000s = root.find("./genre[@category='Action']/decade[@years='2000s']")
dec2000s.append(xmen)
dec1990s = root.find("./genre[@category='Action']/decade[@years='1990s']")
dec1990s.remove(xmen)
Build XML Documents
Nice, so you were able to essentially move an entire movie to a new decade. Save your changes back to the XML.
tree.write("movies.xml")tree = ET.parse('movies.xml')
root = tree.getroot()print(ET.tostring(root, encoding='utf8').decode('utf8'))
Conclusion
ElementTree is an important Python library that allows you to parse and navigate an XML document. Using ElementTree breaks down the XML document in a tree structure that is easy to work with. When in doubt, print it out ( print(ET.tostring(root, encoding=’utf8′).decode(‘utf8’)) ) — use this helpful print statement to view the entire XML document at once.
References
- Original Post as published by Steph Howson: Datacamp
- Python 3 Documentation: ElementTree
- Wikipedia: XML
Modify XML files with Python
Python|Modifying/Parsing XML
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.The design goals of XML focus on simplicity, generality, and usability across the Internet.It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.
XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree.To perform any operations like parsing, searching, modifying an XML file we use a module xml.etree.ElementTree .It has two classes.ElementTree represents the whole XML document as a tree which helps while performing the operations. Element represents a single node in this tree.Reading and writing from the whole document are done on the ElementTree level.Interactions with a single XML element and its sub-elements are done on the Element level.
Properties of Element:
Properties | Description |
---|---|
Tag | String identifying what kind of data the element represents. Can be accessed using elementname.tag. |
Number of Attributes | Stored as a python dictionary. Can be accesses by elementname.attrib. |
Text string | String information regarding the element. |
Child string | Optional child elements string information. |
Child Elements | Number of child elements to a particular root. |
PARSING:
We can parse XML data from a string or an XML document.Considering xml.etree.ElementTree as ET.
1. ET.parse(‘Filename’).getroot() -ET.parse(‘fname’)-creates a tree and then we extract the root by .getroot().
2. ET.fromstring(stringname) -To create a root from an XML data string.
Example 1:
XML document: