How to implement a simple XML database in Python
Answer: Use Python's xml.etree.ElementTree module to build a lightweight XML database, suitable for storing configuration or small-scale data. 1. Design the XML structure, such as book information including title, author, year and other fields; 2. Use ET.parse() to load the XML file and parse it into a tree structure, and traverse the data through root.findall(); 3. Use ET.SubElement to create new elements when adding records and write them back to the file; 4. Search, update or delete data by finding matching items and modifying node content, and call tree.write() after each operation to persist and save. This solution is suitable for low concurrency scenarios, and professional databases such as SQLite should be used for large applications.

Building a simple XML database in Python is straightforward using the built-in xml.etree.ElementTree module. This approach lets you store, retrieve, and modify structured data using XML as the storage format—ideal for lightweight applications, configuration files, or small-scale data persistence.
1. Design Your XML Structure
Start by defining how your data will be organized. For example, if you're storing books, each book can be an element with child elements like title, author, and year.
Sample structure ( books.xml ):
<?xml version="1.0"?>
<library>
<book id="1">
<title>Python Basics</title>
<author>John Doe</author>
<year>2021</year>
</book>
<book id="2">
<title>Advanced Python</title>
<author>Jane Smith</author>
<year>2023</year>
</book>
</library>
2. Load and Parse the XML File
Use ElementTree to read and parse the XML file into a tree structure you can navigate.
import xml.etree.ElementTree as ET
<p>tree = ET.parse('books.xml')
root = tree.getroot()</p>
root now represents the top-level
for book in root.findall('book'):
title = book.find('title').text
author = book.find('author').text
year = book.find('year').text
print(f"{title} by {author}, {year}")
3.Add New Records
To insert a new book, create a new element and append it to the root:
def add_book(title, author, year):
#Create new book element
book = ET.SubElement(root, 'book')
book.set('id', str(len(root) 1)) # Simple ID assignment
<pre class='brush:php;toolbar:false;'>ET.SubElement(book, 'title').text = title
ET.SubElement(book, 'author').text = author
ET.SubElement(book, 'year').text = str(year)
# Save back to file
tree.write('books.xml', encoding='utf-8', xml_declaration=True)Call it like:
add_book("Learning XML", "Alice Brown", 2024)4. Search and Update Data
Find a book by title and update its year:
def update_book_year(title, new_year):
for book in root.findall('book'):
if book.find('title').text == title:
book.find('year').text = str(new_year)
tree.write('books.xml')
return True
return False
Delete a book by title:
def delete_book(title):
for book in root.findall('book'):
if book.find('title').text == title:
root.remove(book)
tree.write('books.xml')
return True
return False
These functions keep changes persistent by writing the updated tree back to the file.
Basically, this gives you a functional mini-database. It's not suitable for high-concurrency or large datasets, but it's perfect for local tools or prototypes. Use proper databases like SQLite for more robust needs.
The above is the detailed content of How to implement a simple XML database in Python. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20529
7
13639
4
ORA-01017: invalid username/password; logon denied
Aug 16, 2025 pm 01:04 PM
When encountering an ORA-01017 error, it means that the login is denied. The main reason is that the user name or password is wrong or the account status is abnormal. 1. First, manually check the user name and password, and note that the upper and lower case and special characters must be wrapped in double quotes; 2. Confirm that the connected service name or SID is correct, and you can connect through tnsping test; 3. Check whether the account is locked or the password expires, and the DBA needs to query the dba_users view to confirm the status; 4. If the account is locked or expired, you need to execute the ALTERUSER command to unlock and reset the password; 5. Note that Oracle11g and above versions are case-sensitive by default, and you need to ensure that the input is accurate. 6. When logging in to special users such as SYS, you should use the assysdba method to ensure the password.
How to show all databases in MySQL
Aug 08, 2025 am 09:50 AM
To display all databases in MySQL, you need to use the SHOWDATABASES command; 1. After logging into the MySQL server, you can execute the SHOWDATABASES; command to list all databases that the current user has permission to access; 2. System databases such as information_schema, mysql, performance_schema and sys exist by default, but users with insufficient permissions may not be able to see it; 3. You can also query and filter the database through SELECTSCHEMA_NAMEFROMinformation_schema.SCHEMATA; for example, excluding the system database to only display the database created by users; make sure to use
How to view table constraints?
Aug 31, 2025 am 01:24 AM
To view the constraints of a table, the core method is to query the database's metadata or information schema. 1. Use INFORMATION_SCHEMA query. For example, in MySQL, you can view the primary key through SELECTCOLUMN_NAMEFROMINFORMATION_SCHEMA.KEY_COLUMN_USAGEWHERETABLE_NAME='your_table_name'ANDCONSTRAINT_NAME='PRIMARY', and change the condition to 'FOREIGNKEY' in foreign keys; 2. Use the database's own commands, such as DESCRIBEtable_name or SH in MySQL
XML Data Binding with Castor in Java
Aug 15, 2025 am 03:43 AM
CastorenablesXML-to-Javaobjectmappingviadefaultconventionsorexplicitmappingfiles;1)DefineJavaclasseswithgetters/setters;2)UseUnmarshallertoconvertXMLtoobjects;3)UseMarshallertoserializeobjectsbacktoXML;4)Forcomplexcases,configurefieldmappingsinmappin
Working with XML attributes vs. elements: design choices
Sep 14, 2025 am 01:21 AM
UseattributesformetadatasuchasID,status,orunit,whichdescribetheelementbutarenotcorecontent,ensuringsimplicityandcompactnesswhendataisatomic.2.Useelementsforactualdatacontent,especiallywhenitmayrequirestructure,repetition,extensibility,orfuturenesting
How Does Redis Scale Differently Than Traditional Databases?
Aug 26, 2025 am 02:15 AM
Redisscalesdifferentlyfromtraditionaldatabasesthroughin-memoryoperations,sharding,andreplication.1)In-memoryoperationsallowRedistohandlehigh-speedread/writetasks.2)Shardingdistributesdataacrossmultipleinstancesforhorizontalscaling.3)Replicationensure
A Guide to XML Canonicalization (C14N)
Aug 27, 2025 am 06:08 AM
XMLCanonicalization(C14N)solvestheproblemofsyntacticvariabilityinXMLbyensuringlogicallyequivalentdocumentsproduceidenticalbytesequences,whichiscriticalfordigitalsignaturesandsecurecomparisons.1.CanonicalXML(C1.0)providesfullnormalizationwithattribute
A Comparison of XML Libraries in the Python Ecosystem
Sep 09, 2025 am 02:19 AM
ForbasicXMLtaskswithnodependencies,usexml.etree.ElementTree;2.ForadvancedfeatureslikeXPathandXSLT,chooselxml;3.Forverylargefiles,usexml.saxorlxml’siterparseformemoryefficiency;4.Forlearningorlegacycode,xml.dom.minidomisacceptable;5.Formalformedorinco





