Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!XML is a portable, open-source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language.
What is XML?
The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.
XML is extremely useful for keeping track of small to medium amounts of data without requiring an SQL- based backbone.
XML Parser Architectures and APIs.
The Python standard library provides a minimal but useful set of interfaces to work with XML. All the submodules for XML processing are available in the xml package.
-
xml.etree.ElementTree − the ElementTree API, a simple and lightweight XML processor
-
xml.dom − the DOM API definition.
-
xml.dom.minidom − a minimal DOM implementation.
-
xml.dom.pulldom − support for building partial DOM trees.
-
xml.sax − SAX2 base classes and convenience functions.
-
xml.parsers.expat − the Expat parser binding.
The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.
-
Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from the disk and the entire file is never stored in the memory.
-
Document Object Model (DOM) − This is a World Wide Web Consortium recommendation wherein the entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.
SAX obviously cannot process information as fast as DOM, when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on many small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other, there is no reason why you cannot use them both for large projects.
For all our XML code examples, let us use a simple XML file movies.xml as an input −
Parsing XML with SAX APIs
SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX generally requires you to create your own ContentHandler by subclassing xml.sax.ContentHandler.
Your ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A ContentHandler object provides methods to handle various parsing events. Its owning parser calls ContentHandler methods as it parses the XML file.
The methods startDocument and endDocument are called at the start and the end of the XML file. The method characters(text) is passed the character data of the XML file via the parameter text.
The ContentHandler is called at the start and end of each element. If the parser is not in namespace mode, the methods startElement(tag, attributes) andendElement(tag) are called; otherwise, the corresponding methodsstartElementNS and endElementNS are called. Here, tag is the element tag, and attributes is an Attributes object.
Here are other important methods to understand before proceeding −
The make_parser Method
The following method creates a new parser object and returns it. The parser object created will be of the first parser type, the system finds.
Here is the detail of the parameters −
-
parser_list − The optional argument consisting of a list of parsers to use, which must all implement the make_parser method.
The parse Method
The following method creates a SAX parser and uses it to parse a document.
Here are the details of the parameters −
-
xmlfile − This is the name of the XML file to read from.
-
contenthandler − This must be a ContentHandler object.
-
errorhandler − If specified, errorhandler must be a SAX ErrorHandler object.
The parseString Method
There is one more method to create a SAX parser and to parse the specifiedXML string.
Here are the details of the parameters −
-
xmlstring − This is the name of the XML string to read from.
-
contenthandler − This must be a ContentHandler object.
-
errorhandler − If specified, errorhandler must be a SAX ErrorHandler object.
Example
This would produce the following result −
*****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Year: 2003 Rating: PG Stars: 10 Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Year: 1989 Rating: R Stars: 8 Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Stars: 10 Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Stars: 2 Description: Viewable boredom
For a complete detail on SAX API documentation, please refer to standard Python SAX APIs.
Parsing XML with DOM APIs
The Document Object Model ("DOM") is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying the XML documents.
The DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another.
Here is the easiest way to load an XML document quickly and to create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file.
The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file, designated by file into a DOM tree object.
This would produce the following output −
Root element : New Arrivals *****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Rating: PG Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Rating: R Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Description: Viewable boredom
For a complete detail on DOM API documentation, please refer to standard Python DOM APIs.
ElementTree XML API
The xml package has an ElementTree module. This is a simple and lightweight XML processor API.
XML is a tree-like hierarchical data format. The 'ElementTree' in this module treats the whole XML document as a tree. The 'Element' class represents a single node in this tree. Reading and writing operations on XML files are done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level.
Create an XML File
The tree is a hierarchical structure of elements starting with root followed by other elements. Each element is created by using the Element() function of this module.
Each element is characterized by a tag and attrib attribute which is a dict object. For tree's starting element, attrib is an empty dictionary.
You may now set up one or more child elements to be added under the root element. Each child may have one or more sub elements. Add them using the SubElement() function and define its text attribute.
Each child is added to root by append() function as −
After adding required number of child elements, construct a tree object by elementTree() function −
The entire tree structure is written to a binary file by tree object's write() function −
Example
In this example, a tree is constructed out of a list of dictionary items. Each dictionary item holds key-value pairs describing a student data structure. The tree so constructed is written to 'myfile.xml'
The 'myfile.xml' is stored in current working directory.
Parse an XML File
Let us now read back the 'myfile.xml' created in above example. For this purpose, following functions in ElementTree module will be used −
ElementTree() − This function is overloaded to read the hierarchical structure of elements to a tree objects.
getroot() − This function returns root element of the tree.
You can obtain the list of sub-elements one level below of an element.
In the following example, elements and sub-elements of the 'myfile.xml' are parsed into a list of dictionary items.
Example
It will produce the following output −
[{'name': 'aaa', 'age': '21', 'sal': '5000'}, {'name': 'xyz', 'age':'22', 'sal': '6000'}]
Modify an XML file
We shall use iter() function of Element. It creates a tree iterator for given tag with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order.
Let us build iterator for all 'marks' subelements and increment text of each sal tag by 100.
Our 'employees.xml' will now be modified accordingly. We can also use set() to update value of a certain key.
x.set(marks, str(mark))
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.