Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to generate XML using Python?
Python provides multiple ways to generate XML documents. The most common approaches are using the dicttoxml package to convert dictionaries to XML, or using Python's built-in xml.etree.ElementTree module for more control.
Method 1: Using dicttoxml Package
First, install the dicttoxml package ?
$ pip install dicttoxml
Basic XML Generation
Convert a dictionary to XML using the dicttoxml method ?
import dicttoxml
data = {
'foo': 45,
'bar': {
'baz': "Hello"
}
}
xml = dicttoxml.dicttoxml(data)
print(xml)
b'<?xml version="1.0" encoding="UTF-8" ?><root><foo type="int">45</foo><bar type="dict"><baz type="str">Hello</baz></bar></root>'
Pretty Printing XML
Format the XML output for better readability using toprettyxml ?
import dicttoxml
from xml.dom.minidom import parseString
data = {
'foo': 45,
'bar': {
'baz': "Hello"
}
}
xml = dicttoxml.dicttoxml(data)
dom = parseString(xml)
print(dom.toprettyxml())
<?xml version="1.0" ?>
<root>
<foo type="int">45</foo>
<bar type="dict">
<baz type="str">Hello</baz>
</bar>
</root>
Method 2: Using xml.etree.ElementTree
Python's built-in ElementTree module provides more control over XML structure ?
import xml.etree.ElementTree as ET
# Create root element
root = ET.Element("root")
# Add child elements
foo_elem = ET.SubElement(root, "foo")
foo_elem.text = "45"
bar_elem = ET.SubElement(root, "bar")
baz_elem = ET.SubElement(bar_elem, "baz")
baz_elem.text = "Hello"
# Generate XML string
xml_string = ET.tostring(root, encoding='unicode')
print(xml_string)
<root><foo>45</foo><bar><baz>Hello</baz></bar></root>
Comparison
| Method | Setup Required | Best For |
|---|---|---|
| dicttoxml | pip install | Quick dictionary conversion |
| ElementTree | Built-in | Custom XML structure control |
Conclusion
Use dicttoxml for quick dictionary-to-XML conversion with automatic type detection. Use ElementTree when you need precise control over XML structure and attributes.
Advertisements
