XML configuration files provide a structured, hierarchical way to store application settings, server credentials, and logging parameters.
Python's built-in ElementTree module allows developers to read, write, modify, and integrate XML-based configurations with databases effortlessly.
<config>
<server>
<host>127.0.0.1</host>
<port>8080</port>
</server>
<logging>
<level>DEBUG</level>
<file>app.log</file>
</logging>
<user>
<theme>dark</theme>
<language>en</language>
</user>
</config>
import xml.etree.ElementTree as ET
# Parse the XML file
tree = ET.parse('config.xml')
root = tree.getroot()
# Access specific elements
host = root.find('./server/host').text
port = root.find('./server/port').text
log_level = root.find('./logging/level').text
print(f"Host: {host}")
print(f"Port: {port}")
print(f"Log Level: {log_level}")
# Modify an element
root.find('./logging/level').text = 'INFO'
# Save changes back to the file
tree.write('config.xml')
import xml.etree.ElementTree as ET
# Create root element
config = ET.Element('config')
# Add child elements
server = ET.SubElement(config, 'server')
ET.SubElement(server, 'host').text = '192.168.1.1'
ET.SubElement(server, 'port').text = '9090'
logging = ET.SubElement(config, 'logging')
ET.SubElement(logging, 'level').text = 'DEBUG'
ET.SubElement(logging, 'file').text = 'error.log'
# Save to a file
tree = ET.ElementTree(config)
tree.write('new_config.xml')
Storing database credentials in an XML file keeps sensitive connection strings out of source code. This example connects to a MySQL database using SQLAlchemy.
<configuration>
<database>
<engine>mysql+pymysql</engine>
<username>your_username</username>
<password>your_password</password>
<host>localhost</host>
<port>3306</port>
<db_name>your_database</db_name>
</database>
</configuration>
import xml.etree.ElementTree as ET
from sqlalchemy import create_engine, inspect
# Parse configuration XML
tree = ET.parse('db_config.xml')
root = tree.getroot()
db_config = root.find('database')
engine_type = db_config.find('engine').text
username = db_config.find('username').text
password = db_config.find('password').text
host = db_config.find('host').text
port = db_config.find('port').text
db_name = db_config.find('db_name').text
# Construct connection URL
connection_url = f"{engine_type}://{username}:{password}@{host}:{port}/{db_name}"
try:
engine = create_engine(connection_url)
connection = engine.connect()
print("Connection to the database was successful.")
# Use inspect() for SQLAlchemy 2.0 schema introspection
inspector = inspect(engine)
tables = inspector.get_table_names()
print("Tables in the database:", tables)
connection.close()
except Exception as e:
print(f"Error: {e}")
config.xml.template) in version control while excluding actual credentials.XML is a robust, flexible format for storing application configuration data. Python's ElementTree and SQLAlchemy make managing and connecting via XML configurations straightforward and secure.
Practice XML configuration management in our companion Jupyter Notebook:
Explore interactive code cells and test reading, modifying, and creating XML configuration files.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.