Python3 XML Parsing
What is XML?
Section titled “What is XML?”XML stands for eXtensible Markup Language, a subset of the Standard Generalized Markup Language, and is a markup language used to mark electronic documents to make them structural. You can learn XML through this site’s XML Tutorial.
XML is designed to transmit and store data.
XML is a set of rules for defining semantic markup, which divides documents into many parts and identifies those parts.
It is also a meta-markup language, that is, a language that defines the syntactic language used to define other domain-specific, semantic, structural markup languages.
Python’s XML Parsing
Section titled “Python’s XML Parsing”Common XML programming interfaces include DOM and SAX. These two interfaces handle XML files differently and, of course, are used in different situations.
Python has three methods for parsing XML: ElementTree, SAX, and DOM.
1. ElementTree
Section titled “1. ElementTree”xml.etree.ElementTree is a module in the Python standard library for processing XML. It provides a simple and efficient API for parsing and generating XML documents.
2. SAX (simple API for XML)
Section titled “2. SAX (simple API for XML)”The Python standard library includes a SAX parser. SAX uses an event-driven model, processing XML files by triggering events one by one during XML parsing and calling user-defined callback functions.
3. DOM (Document Object Model)
Section titled “3. DOM (Document Object Model)”Parses XML data into a tree in memory, and operates on XML by operating on the tree.
The XML example file movies.xml used in this chapter has the following content:
Example
Section titled “Example”Python Using ElementTree to Parse XML
Section titled “Python Using ElementTree to Parse XML”xml.etree.ElementTree is a module in the Python standard library for processing XML.
The following are some key concepts and usages of the xml.etree.ElementTree module:
ElementTree and Element Objects:
- ElementTree: The ElementTree class is a tree representation of an XML document. It contains one or more Element objects, representing the entire XML document.
- Element: The Element object is the representation of an element in the XML document. Each element has a tag, a set of attributes, and zero or more child elements.
Parsing XML
Section titled “Parsing XML”fromstring() method: Use the fromstring() method to convert a string containing XML data into an Element object:
Example
Section titled “Example”parse() method: If the XML data is stored in a file, you can use the parse() method to parse the entire XML document:
Traversing the XML Tree
Section titled “Traversing the XML Tree”find() method: Use the find() method to find the first child element with a specified tag:
findall() method: Use the findall() method to find all child elements with a specified tag:
Accessing Element Attributes and Text Content
Section titled “Accessing Element Attributes and Text Content”attrib property: Access element attributes through the attrib property:
text property: Access the text content of an element through the text property:
Creating XML
Section titled “Creating XML”Element() constructor: Use the Element() constructor to create new elements:
SubElement() function: Use the SubElement() function to create child elements with a specified tag:
Modifying XML
Section titled “Modifying XML”Modifying element attributes and text content: Directly modify the element’s attrib and text properties.
Removing elements: Use the remove() method to remove elements:
Simple reading of XML content:
Example
Section titled “Example”The output of the above code is:
Next, we will create an XML document containing book information, then use the module for parsing and manipulation:
Example
Section titled “Example”In the above example, we first create an XML document containing information about two books. Then we save this document to the file books.xml. Next, we use the ET.parse() method to parse the XML document from the file, traverse the document tree, and extract and print the title, author, and price information for each book.
Python Using SAX to Parse XML
Section titled “Python Using SAX to Parse XML”SAX is an event-driven API.
Using SAX to parse XML documents involves two parts: the parser and the event handler.
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 the events and processing the transmitted XML data.
-
- For processing large files;
-
- When only part of the file’s content is needed, or only specific information from the file is needed.
-
- When you want to build your own object model.
To use the SAX method to process XML in Python, you need to first import the parse function from xml.sax and the ContentHandler from xml.sax.handler.
ContentHandler Class Methods Introduction
Section titled “ContentHandler Class Methods Introduction”characters(content) method
Call timing:
From the beginning of a line, before encountering a tag, if there are characters, the value of content is these strings.
From one tag, before encountering the next tag, if there are characters, the value of content is these strings.
From one tag, before encountering a line terminator, if there are characters, the value of content is these strings.
A tag can be either a start tag or an end tag.
startDocument() method
Called when the document starts.
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 name, and attrs is the tag’s attribute value dictionary.
endElement(name) method
Called when an XML end tag is encountered.
make_parser Method
Section titled “make_parser Method”The following method creates a new parser object and returns it.
Parameter description:
- parser_list - Optional parameter, parser list
parser Method
Section titled “parser Method”The following method creates a SAX parser and parses an XML document:
Parameter description:
- xmlfile - XML file name
- contenthandler - Must be a ContentHandler object
- errorhandler - If this parameter is specified, errorhandler must be a SAX ErrorHandler object
parseString Method
Section titled “parseString Method”The parseString method creates an XML parser and parses an XML string:
Parameter description:
- xmlstring - XML string
- contenthandler - Must be a ContentHandler object
- errorhandler - If this parameter is specified, errorhandler must be a SAX ErrorHandler object
Python XML Parsing Example
Section titled “Python XML Parsing Example”Example
Section titled “Example”The output of the above code is:
For the complete SAX API documentation, please refer to Python SAX APIs
Using xml.dom to Parse XML
Section titled “Using xml.dom to Parse XML”The Document Object Model (DOM) is a standard programming interface recommended by the W3C for processing extensible markup languages.
When a DOM parser parses an XML document, it reads the entire document at once, saves all elements in the document in a tree structure in memory, and then you can use the different functions provided by DOM to read or modify the content and structure of the document, and can also write the modified content back to the XML file.
In Python, xml.dom.minidom is used to parse XML files. Examples are as follows:
Example
Section titled “Example”The output of the above program is:
For the complete DOM API documentation, please refer to Python DOM APIs.