Pandas to_xml(): Export DataFrame to an XML File

DataFrame to XML file by to_xml()
The `to_xml()` function in Pandas allows you to export a DataFrame to an XML file. It supports options like setting the root tag, row tag, and handling namespaces. Here are examples to help you use this function effectively. ---

Basic Example

Convert a simple DataFrame into an XML file:

import pandas as pd

# Sample DataFrame
data = {
    'id': [1, 2, 3],
    'name': ['John Deo', 'Max Ruin', 'Arnold'],
    'class': ['Four', 'Three', 'Three'],
    'mark': [75, 85, 55],
    'gender': ['female', 'male', 'male']
}
df = pd.DataFrame(data)

# Convert to XML
my_xml = df.to_xml('E:\\testing\\data\\student_output.xml',index=False)
### Output: The file `student_output.xml` will contain:

<?xml version='1.0' encoding='utf-8'?>
<Root>
  <Row>
    <id>1</id>
    <name>John Deo</name>
    <class>Four</class>
    <mark>75</mark>
    <gender>female</gender>
  </Row>
  <Row>
    <id>2</id>
    <name>Max Ruin</name>
    <class>Three</class>
    <mark>85</mark>
    <gender>male</gender>
  </Row>
  <Row>
    <id>3</id>
    <name>Arnold</name>
    <class>Three</class>
    <mark>55</mark>
    <gender>male</gender>
  </Row>
</Root>
---

Converting Pandas DataFrame to XML with Customization

Learn how to export a Pandas DataFrame to XML format with full control over attributes like root name, row name, XML declaration, and pretty-printing for enhanced readability.

import pandas as pd

# Sample DataFrame
data = {
    'id': [1, 2, 3],
    'name': ['John Deo', 'Max Ruin', 'Arnold'],
    'class': ['Four', 'Three', 'Three'],
    'mark': [75, 85, 55],
    'gender': ['female', 'male', 'male']
}
df = pd.DataFrame(data)

# Convert to XML with all attributes explicitly set
df.to_xml(
    path_or_buffer='student_custom.xml', 
    index=False, 
    root_name='Students', 
    row_name='Student', 
    xml_declaration=True,  # Include XML declaration
    pretty_print=True      # Format XML for readability
)
### Output:

<?xml version='1.0' encoding='utf-8'?>
<Students>
  <Student>
    <id>1</id>
    <name>John Deo</name>
    <class>Four</class>
    <mark>75</mark>
    <gender>female</gender>
  </Student>
  <Student>
    <id>2</id>
    <name>Max Ruin</name>
    <class>Three</class>
    <mark>85</mark>
    <gender>male</gender>
  </Student>
  <Student>
    <id>3</id>
    <name>Arnold</name>
    <class>Three</class>
    <mark>55</mark>
    <gender>male</gender>
  </Student>
</Students>
---

Attributes in to_xml()

Here is a table explaining the commonly used attributes of `to_xml()`:
Attribute Default Value Description
path_or_buffer None The file path or buffer where the XML output will be written.
index True Whether to include the DataFrame index in the XML output.
root_name 'Root' The name of the root element in the XML.
row_name 'Row' The name of each row element in the XML.
xml_declaration True Whether to include the XML declaration at the beginning of the file.
pretty_print True Format the XML output for better readability.
---

Example: Including the Index

To include the DataFrame index in the XML file, set `index=True`:
df.to_xml('student_with_index.xml',index=True)
### Output:

<?xml version='1.0' encoding='utf-8'?>
<Root>
  <Row>
    <index>0</index>
    <id>1</id>
    <name>John Deo</name>
    <class>Four</class>
    <mark>75</mark>
    <gender>female</gender>
  </Row>
  <Row>
    <index>1</index>
    <id>2</id>
    <name>Max Ruin</name>
    <class>Three</class>
    <mark>85</mark>
    <gender>male</gender>
  </Row>
</Root>
---

Database table to XML file

Read data from student table from MySQL ( update the Step 1, the connection part ) or SQLite database to create a DataFrame. Using the to_xml() create one xml file from the DataFrame.

from sqlalchemy import create_engine
import pandas as pd

# Step 1: Connect to the SQLite database using SQLAlchemy
engine = create_engine('sqlite:///F:/testing/sqlite/my_db.db')  # Replace with your database path

# Step 2: Read the student table into a DataFrame
query = 'SELECT * FROM student'
df = pd.read_sql_query(query, engine.connect())

# Step 3: Export the DataFrame to an XML file
df.to_xml(
    path_or_buffer='F:/testing/sqlite/student.xml', 
    parser='etree', 
    index=False, 
    root_name='Students', 
    row_name='Student', 
    xml_declaration=True,  # Include XML declaration
    pretty_print=True      # Format XML for readability
)

# Print success message
print("Data successfully exported to student.xml")

Questions

Back to Pandas Input/Output read_xml() Function Learn More About XML
Data Import Export using Tkitner GUI and Pandas DataFrame
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    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 FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer