Using XML as Configuration Files in Python

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.

1. Why Use XML for Configuration?

  • Readability: Human-readable markup structure makes settings easy to inspect and update.
  • Hierarchical Organization: Logical nesting groups related settings (e.g., server parameters, database credentials).
  • Extensibility: New settings and attributes can be added seamlessly without breaking existing parsers.

2. Working with XML Configuration Files in Python

Sample XML Configuration File (`config.xml`)

<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>

Reading XML Configuration

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}")

Modifying XML Configuration

# Modify an element
root.find('./logging/level').text = 'INFO'

# Save changes back to the file
tree.write('config.xml')

Creating XML Configuration Programmatically

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')

3. Using XML Configuration to Connect to MySQL via SQLAlchemy

Storing database credentials in an XML file keeps sensitive connection strings out of source code. This example connects to a MySQL database using SQLAlchemy.

XML Database Config (`db_config.xml`)

<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>

Python Connection Script & Schema Introspection

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}")

4. Best Practices

  • Separation of Concerns: Keep database credentials and environment settings isolated in configuration files.
  • Backups & Version Control: Maintain sample configuration templates (e.g., config.xml.template) in version control while excluding actual credentials.

Conclusion

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.

Interactive Notebook & Practice Exercises

Practice XML configuration management in our companion Jupyter Notebook:

Interactive Companion Jupyter Notebook

Explore interactive code cells and test reading, modifying, and creating XML configuration files.

View on GitHub Open In Colab



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer