Python XML Parsing
What is XML?
XML stands for eXtensible Markup Language). You can learn through this site XML Tutorial
XML is designed to transport and store data.
XML is a set of rules for defining semantic tags that divide a document into many parts and identify those parts.
It is also a meta-markup language, that is, a syntactic language that defines other domain-specific, semantic, structured markup languages.
Parsing XML with Python
The common XML programming interfaces are DOM and SAX; these two interfaces handle XML files differently and are therefore used in different situations.
Python has three ways to parse XML: SAX, DOM, and ElementTree:
1.SAX (simple API for XML )
The Python standard library includes the SAX parser. SAX uses an event-driven model, processing XML files by triggering events one by one during parsing and calling user-defined callback functions.
2.DOM(Document Object Model)
Parse the XML data into a tree in memory, and manipulate the XML by operating on the tree.
3. ElementTree
ElementTree is like a lightweight DOM, with a convenient and friendly API. It has good code usability, fast speed, and low memory consumption.
**Note:** Because DOM needs to map XML data into a tree in memory, it is relatively slow and memory-intensive, while SAX reads XML files in a stream, which is faster and uses less memory, but requires the user to implement callback functions (handlers).
The content of the XML example file movies.xml used in this chapter is as follows:
movies.xml
<
collection
shelf
=
"
New Arrivals
"
<
movie
title
=
"
Enemy Behind
"
<
type
War, Thriller
type
<
format
DVD
format
<
year
2003
year
<
rating
PG
rating
<
stars
10
stars
<
description
Talk about a US-Japan war
description
movie
<
movie
title
=
"
Transformers
"
<
type
Anime, Science Fiction
type
<
format
DVD
format
<
year
1989
year
<
rating
R
rating
<
stars
8
stars
<
description
A schientific fiction
description
movie
<
movie
title
=
"
Trigun
"
<
type
Anime, Action
type
<
format
DVD
format
<
episodes
4
episodes
<
rating
PG
rating
<
stars
10
stars
<
description
Vash the Stampede!
description
movie
<
movie
title
=
"
Ishtar
"
<
type
Comedy
type
<
format
VHS
format
<
rating
PG
rating
<
stars
2
stars
<
description
Viewable boredom
description
movie
collection
Python uses SAX to parse XML
SAX is an event-driven API.
Parsing an XML document with SAX involves two parts: the parserandEvent handlers.
The parser is responsible for reading the XML document and sending events to the event handler, such as element start and element end events.
The event handler is responsible for responding to events and processing the XML data passed to it.
- 1. Processing large files;
- 2. Only needing part of a file's content, or only needing specific information from a file.
- 3. When you want to build your own object model.
To process XML with SAX in Python, you first import the parse function from xml.sax and the ContentHandler from xml.sax.handler.
ContentHandler class methods
characters(content) method
When it is called:
From the start of a line, before a tag is encountered, characters exist and content holds those strings.
From one tag, before the next tag is encountered, characters exist and content holds those strings.
From one tag, before the line ending is encountered, characters exist and content holds those strings.
A tag can be a start tag or an end tag.
The startDocument() method
Called when the document starts.
The endDocument() method
Called when the parser reaches the end of the document.
startElement(name, attrs) method
Called when an XML start tag is encountered; name is the tag's name, and attrs is a dictionary of the tag's attributes.
The endElement(name) method
Called when an XML end tag is encountered.
make_parser method
The following method creates a new parser object and returns it.
xml.sax.make_parser( [parser_list] )
Parameter description:
- parser_list - optional parameter, a list of parsers
parser method
The following method creates a SAX parser and parses an xml document:
xml.sax.parse( xmlfile, contenthandler[, errorhandler])
Parameter description:
- xmlfile - the xml filename
- contenthandler - Must be a ContentHandler object
- errorhandler - If specified, errorhandler must be a SAX ErrorHandler object
parseString method
The parseString method creates an XML parser and parses an XML string:
xml.sax.parseString(xmlstring, contenthandler[, errorhandler])
Parameter description:
- xmlstring - the xml string
- contenthandler - Must be a ContentHandler object
- errorhandler - If specified, errorhandler must be a SAX ErrorHandler object
Python XML parsing example
Example
The result of executing the above code is as follows:
*****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 the complete SAX API documentation, seePython SAX APIs
Parsing xml with xml.dom
The Document Object Model (DOM) is a standard programming interface recommended by the W3C for handling extensible markup languages.
When a DOM parser parses an XML document, it reads the entire document at once and stores all elements in a tree structure in memory; afterwards you can use the various functions DOM provides to read or modify the document's content and structure, and write the modified content back to an xml file.
Parsing XML files with xml.dom.minidom in Python, example below:
Example
The result of running the above program is as follows:
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 the complete DOM API documentation, seePython DOM APIs.