How to append new data to existing XML using Python ElementTree
Last Updated :
26 Feb, 2024
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 Python ElementTree?
Python's ElementTree
module is part of the standard library and provides a simple and lightweight way to parse, manipulate, and create XML documents. It follows the ElementTree API, allowing you to work with XML in a tree-like structure. The main classes in the ElementTree module are Element
, ElementTree
, and ElementTree.ElementTree
.
Syntax :
import xml.etree.ElementTree as ET
tree = ET.parse('existing_xml_file.xml'); tree.getroot().append(ET.Element('new_element_name'))
Advantages:
Below, are the advantages of Python ElementTree.
- Simplicity: Python ElementTree offers a simple and readable syntax for XML manipulation, making it accessible for developers at all skill levels.
- Standard Library Integration: As part of the Python standard library, ElementTree is readily available without the need for additional installations, ensuring broad compatibility.
- Element Manipulation: The API provides efficient methods for creating, modifying, and deleting XML elements, enabling easy data manipulation within XML documents.
- Namespace Support: ElementTree handles XML namespaces, crucial for working with complex XML structures and standards that use namespaces to avoid naming conflicts.
How to append new data to existing XML using Python ElementTree
Below, are the example of How to append new data to existing XML using Python ElementTree.
Example 1: Appending New Data to Existing XML
app.py : Below, code utilizes the ElementTree module to manipulate an XML file. It first loads an existing XML file ('existing.xml') and obtains the root element of the XML tree. Subsequently, a new XML element named 'new_element' with the text content 'New data' is created and appended to the root. Finally, the modified XML structure is written back to a new file ('data.xml'), reflecting the addition of the new element.
Python
import xml.etree.ElementTree as ET
# Load the XML file
tree = ET.parse('existing.xml')
root = tree.getroot()
# Create a new element
new_element = ET.Element('new_element')
new_element.text = 'New data'
# Append the new element to the root
root.append(new_element)
# Write the modified XML back to the file
tree.write('exisitng.xml')
existing.html: Below, XML code represents a data structure with an existing element containing the text "Existing data" and a new element with the text "New data" encapsulated within a root element named "data."
XML
<data>
<existing_element>Existing data</existing_element>
<new_element>New data</new_element>
</data>
Output :
existing.xml
<data>
<existing_element>Existing data</existing_element>
<new_element>New data</new_element>
<new_element>New data</new_element></data>
Example 2 : Python XML Manipulation: Adding a New Book Entry
app.py : In below code uses the ElementTree module to parse an existing XML file named 'library.xml.' It creates a new book element with attributes such as title, author, and genre, and appends it to the root of the XML tree.Finally, the updated XML tree is written back to a file named 'updated_library.xml.'
Python3
import xml.etree.ElementTree as ET
# Parse the existing XML file
tree = ET.parse('library.xml')
root = tree.getroot()
# Create a new book element
new_book = ET.Element('book')
# Add attributes to the new book element
new_book.set('title', 'New Book Title')
new_book.set('author', 'Author Name')
new_book.set('genre', 'Fiction')
# Append the new book element to the root
root.append(new_book)
# Write the updated XML back to a file
tree.write('library.xml')
library.xml: below XML code with a root element <data>
containing existing and new child elements. <existing_element>
holds "Existing data," and <new_element>
has "New data." Represents a basic XML structure for data storage or exchange.
XML
<data>
<existing_element>Existing data</existing_element>
<new_element>New data</new_element>
</data>
Output
library.xml
<data>
<existing_element>Existing data</existing_element>
<new_element>New data</new_element>
<book title="New Book Title" author="Author Name" genre="Fiction" /></data>
Conclusion
In conclusion , Appending new data to an existing XML file using Python ElementTree is a straightforward process. By following the simple syntax and using the capabilities of the ElementTree module, you can efficiently manipulate and update XML documents in your Python applications. This flexibility makes Python a powerful choice for working with XML data in various scenarios, from data processing to web development.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read