Reading and Writing XML Files in Python
Introduction
XML (stands for Extensible Markup Language), was designed so that it easily can be interpreted by both computers and humans. This language has some set of rules used to encode documents in a certain format. In this article, we will discuss methods that are used to read and write XML files.
Parsing is the process of reading and writing data in an XML file. In Parsing, the logical components of data are analyzed. Therefore when we say reading an XML file, we are referring to parsing the XML file.
In this article, we will see two libraries that are used for XML parsing. These two libraries are:
BeautifulSoup which is used alongside the LXML and XML parsers.
ElementTree Library.
BeautifulSoup
In Python, BeautifulSoup is a library that is used to read and write on an XML file. Now before using this library, we type the following command:
pip install beautifulsoup4 |
Reading Data From an XML File
Two steps are involved while parsing an XML file.
- Finding Tags
- Extracting from tags
Throughout the article, we will use the XML file that is mentioned below.
<?xml version="1.0" encoding="utf-8"?> |
Example 1
from bs4 import BeautifulSoup |
Output
[<unique> |
Example 2
from bs4 import BeautifulSoup |
Output
<?xml version="1.0" encoding="utf-8"?> |
Using Elementree
This module gives us an abundance of tools to manipulate XML files. It is included in python’s standard library. And because of that, the user does not need to install anything externally.
Code
import xml.etree.ElementTree as ET |
Output
<Element 'saranghe' at 0x7fe97c2cee08> |
Writing XML Files
Now, we will have a look at some methods which are used to write data on the XML files. In the code below we have to create a new XML file from the scratch.
Now at first, using ET.Element(‘chess’), we will make a parent tag (root) which will be under the chess. Now when the root is defined, the other subtype elements are made under that root tag. After it using the, we will make a subtag named Opening which will be under the chess tag ET.SubElement(). Now using set() (a tag found under a SubElement(), used to determine the attribute to a tag), under the Opening tag, we will create two more tags namely E4 lying under the E4 and D4 tags. and D4. After it uses the attribute text which is inside the SubElement function, we will add text. Now at last we will convert the data type of the content to bytes objects from the ‘XML.etree.ElementTree.Element’ with the help of a function named as toString(). Lastly, we will flush all the data to a file named gos.xml which will be opened in writing binary mode.
Example
import xml.etree.ElementTree as ET |
Output
<chess> |