The Wayback Machine - https://web.archive.org/web/20240624060740/https://www.geeksforgeeks.org/adding-data-into-existing-xml-file-in-python/
Open In App

Adding Data into Existing XML File in Python

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given an XML existing file and our task is to append new data into that existing XML using Python. In this article, we will see how we can append new data to the existing XML using Python.

Creating an XML file

In this example, an XML tree is constructed using the xml.etree.ElementTree module in Python, where child elements with attributes and text are added to the root element. Finally, the tree is written to a file named “sample.xml”. We will use this file in our article for further operations.

Python3
import xml.etree.ElementTree as ET

# Create the root element
root = ET.Element("data")

# Create a child element with attributes
item = ET.SubElement(root, "item")
item.attrib["id"] = "1"
item.text = "Item 1"

# Create another child element
item = ET.SubElement(root, "item")
item.attrib["id"] = "2"
item.text = "Item 2"

# Create the tree and write it to a file
tree = ET.ElementTree(root)
tree.write("sample.xml")

Output: sample.xml

Capture

sample.xml

Adding Data into Existing XML File in Python

Below are some of the ways by which we can add new data into the existing XML file in Python:

  1. Using ElementTree
  2. Using lxml library
  3. Using xml.dom.minidom

Adding Data into Existing XML Using ElementTree

In this example, the script loads an XML file, adds a new item with an ID and text, then saves the modified XML back to the file using ElementTree in Python.

Python3
import xml.etree.ElementTree as ET

# Load the existing XML file
tree = ET.parse("sample.xml")
root = tree.getroot()

# Append new data
new_item = ET.SubElement(root, "item")
new_item.attrib["id"] = "3"
new_item.text = "Item 3"

# Save the changes back to the file
tree.write("sample.xml")

Output: sample.xml

Capture

Adding Data into Existing XML Using lxml library

In this example, the script utilizes the lxml library to parse an XML file, adds a new item with an ID and text, then saves the modified XML back to the file with formatting.

Python3
from lxml import etree

# Load the existing XML file
tree = etree.parse("sample.xml")
root = tree.getroot()

# Append new data
new_item = etree.SubElement(root, "item")
new_item.attrib["id"] = "3"
new_item.text = "Item 3"

# Save the changes back to the file
tree.write("sample.xml", pretty_print=True)

Output: sample.xml

Capture

Adding Data into Existing XML Using xml.dom.minidom

In this example, using the xml.dom.minidom module, the script loads an XML file, adds a new item with an ID and text, then saves the modified XML back to the file.

Python3
import xml.dom.minidom

# Load the existing XML file
doc = xml.dom.minidom.parse("sample.xml")
root = doc.documentElement

# Append new data
new_item = doc.createElement("item")
new_item.setAttribute("id", "3")
text_node = doc.createTextNode("Item 3")
new_item.appendChild(text_node)
root.appendChild(new_item)

# Save the changes back to the file
with open("sample.xml", "w") as file:
    doc.writexml(file)

Output: sample.xml

Capture

Conclusion

The provided code snippets demonstrate different approaches to appending data to an existing XML file in Python. Whether using the built-in ElementTree module, the lxml library, or xml.dom.minidom, each method achieves the same goal with slight variations in syntax and functionality. These examples offer flexibility for developers to choose the XML manipulation method that best suits their project requirements and preferences.



Similar Reads

How to append new data to existing XML using Python ElementTree
Extensible Markup Language (XML) is a widely used format for storing and transporting data. In Python, the ElementTree module provides a convenient way to work with XML data. When dealing with XML files, it is common to need to append new data to an existing XML document. This can be achieved efficiently using Python's ElementTree module. What is P
4 min read
How to create a duplicate file of an existing file using Python?
In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Pyt
5 min read
Adding new enum column to an existing MySQL table using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to add a new enum column to an existing MySQL table using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python
1 min read
How to get Scrapy Output File in XML File?
Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy provides a fast and efficient method to scrape a website. Web Scraping is used to extract the data from websites. In Scrapy we create a spider and then use it to crawl a website. In this article, we are going to extract population by country data from worldometers website. Let's i
2 min read
Inserting data into a new column of an already existing table in MySQL using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to Inserting data into a new column of an already existing table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector Python modul
2 min read
How to store XML data into a MySQL database using Python?
In this article, we are going to store XML data into the MySQL database using python through XAMPP server. So we are taking student XML data and storing the values into the database. RequirementsXAMPP server: It is a cross-platform web server used to develop and test programs on a local server. It is developed and managed by Apache Friends and is o
3 min read
Adding two columns to existing PySpark DataFrame using withColumn
In this article, we are going to see how to add two columns to the existing Pyspark Dataframe using WithColumns. WithColumns is used to change the value, convert the datatype of an existing column, create a new column, and many more. Syntax: df.withColumn(colName, col) Returns: A new :class:`DataFrame` by adding a column or replacing the existing c
2 min read
Adding new column to existing DataFrame in Pandas
Adding new columns to an existing DataFrame is a fundamental task in data analysis using Pandas. It allows you to enrich your data with additional information and facilitate further analysis and manipulation. This article will explore various methods for adding new columns, including simple assignment, the insert() method, the assign() method. Let'
6 min read
Add a Column to Existing CSV File in Python
Working with CSV files is a common task in data manipulation and analysis, and Python provides versatile tools to streamline this process. Here, we have an existing CSV file and our task is to add a new column to the existing CSV file in Python. In this article, we will see how we can add a column to a CSV file in Python. Add a New Column to Existi
3 min read
Turning a Dictionary into XML in Python
XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elements in an XML are contained in an outermost element
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg