Python minidom
last modified November 30, 2026 Python 3.15
In this article we show how to work with XML documents using the
xml.dom.minidom module.
The minidom module is a minimal implementation of the
Document Object Model (DOM), the W3C interface for XML that is also
used in JavaScript, Java, and other languages. A parsed document is a
tree of nodes: the document itself, elements, text, comments, and a
few other node types. Methods such as
getElementsByTagName, appendChild, and
createElement work the same way as in a web browser.
The DOM is more verbose than the Pythonic ElementTree API, which is usually the better choice for new code. The minidom module is useful when we port DOM code from another language, when we need to keep comments and processing instructions, or when we already know the DOM from the browser. Like ElementTree, it loads the whole document into memory; for streaming, see SAX.
Parsing a string
The parseString function parses XML text and returns a
Document object.
from xml.dom import minidom
data = """<languages>
<language>Python</language>
<language>Ada</language>
<language>Fortran</language>
</languages>"""
doc = minidom.parseString(data)
root = doc.documentElement
print(root.tagName)
for lang in root.getElementsByTagName('language'):
print(lang.firstChild.data)
The program prints the name of the root element and the text of each
language element.
doc = minidom.parseString(data) root = doc.documentElement print(root.tagName)
The Document is not the root element itself; the root is
available as documentElement. The
tagName attribute holds the element's name.
for lang in root.getElementsByTagName('language'):
print(lang.firstChild.data)
The getElementsByTagName method returns all descendant
elements with the given name. In the DOM, the text of an element is not
an attribute of the element; it is a separate text node. We get it as
the data of the element's first child.
$ python first.py languages Python Ada Fortran
Parsing a file
The parse function reads a file name or an open file. We
use the following document in several examples.
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product id="1" category="drinks">
<name>Green tea</name>
<price>4.50</price>
<quantity>30</quantity>
</product>
<product id="2" category="drinks">
<name>Coffee</name>
<price>7.90</price>
<quantity>12</quantity>
</product>
<product id="3" category="food">
<name>Rye bread</name>
<price>2.20</price>
<quantity>0</quantity>
</product>
<product id="4" category="food">
<name>Honey</name>
<price>6.75</price>
<quantity>8</quantity>
</product>
<product id="5" category="drinks">
<name>Cocoa</name>
<price>5.10</price>
<quantity>0</quantity>
</product>
</products>
Each product has the id and category
attributes and three child elements.
from xml.dom import minidom
def child_text(parent, tag):
return parent.getElementsByTagName(tag)[0].firstChild.data
doc = minidom.parse('products.xml')
products = doc.getElementsByTagName('product')
print(f'{products.length} products')
for product in products:
pid = product.getAttribute('id')
name = child_text(product, 'name')
price = float(child_text(product, 'price'))
qty = int(child_text(product, 'quantity'))
print(f'{pid:>2} {name:<10} {price:6.2f} {qty:4}')
The program prints the products as a table.
def child_text(parent, tag):
return parent.getElementsByTagName(tag)[0].firstChild.data
Reading the text of a child element takes three steps in the DOM, so we put them into a small helper function.
products = doc.getElementsByTagName('product')
print(f'{products.length} products')
The result is a NodeList. It is a Python list with an
extra length attribute from the DOM standard; the
len function works too.
pid = product.getAttribute('id')
The getAttribute method returns the value of an attribute
as a string.
$ python read_file.py 5 products 1 Green tea 4.50 30 2 Coffee 7.90 12 3 Rye bread 2.20 0 4 Honey 6.75 8 5 Cocoa 5.10 0
The node tree
Every part of the document is a node. The whitespace between elements is kept as text nodes, so the children of an element are often not what we expect.
from xml.dom import minidom
from xml.dom.minidom import Node
data = """<product id="1">
<!-- best seller -->
<name>Green tea</name>
<price>4.50</price>
</product>"""
product = minidom.parseString(data).documentElement
for node in product.childNodes:
print(f'{node.nodeType:2} {node.nodeName:10} {node.nodeValue!r}')
print()
elements = [n for n in product.childNodes if n.nodeType == Node.ELEMENT_NODE]
for e in elements:
print(e.tagName, e.firstChild.nodeValue)
The program lists all child nodes of a product and then only its elements.
for node in product.childNodes:
print(f'{node.nodeType:2} {node.nodeName:10} {node.nodeValue!r}')
The childNodes attribute contains all direct children. The
nodeType is a number, nodeName is the tag
name for elements and a fixed name such as #text for other
nodes, and nodeValue is the content of text and comment
nodes and None for elements.
elements = [n for n in product.childNodes if n.nodeType == Node.ELEMENT_NODE]
The Node class defines constants for the node types. We
compare nodeType with Node.ELEMENT_NODE to
skip the whitespace and the comment.
$ python node_tree.py 3 #text '\n ' 8 #comment ' best seller ' 3 #text '\n ' 1 name None 3 #text '\n ' 1 price None 3 #text '\n' name Green tea price 4.50
Element text
Taking firstChild.data works only for an element that
contains exactly one piece of text. Mixed content consists of several
nodes, and an empty element has no child at all.
from xml.dom import minidom
from xml.dom.minidom import Node
def text_of(element):
parts = []
for node in element.childNodes:
if node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
parts.append(node.data)
elif node.nodeType == Node.ELEMENT_NODE:
parts.append(text_of(node))
return ''.join(parts)
doc = minidom.parseString(
'<p>Read <b>this</b> twice.<note/><![CDATA[a < b]]></p>')
p = doc.documentElement
print(repr(p.firstChild.data))
print(repr(text_of(p)))
note = doc.getElementsByTagName('note')[0]
print(note.firstChild)
print(repr(text_of(note)))
The text_of function collects the text of an element and
all its descendants.
if node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
parts.append(node.data)
elif node.nodeType == Node.ELEMENT_NODE:
parts.append(text_of(node))
Text can be stored in text nodes and in CDATA sections. For child elements, the function calls itself.
print(repr(p.firstChild.data))
The first child of the paragraph holds only the text before the
b element.
note = doc.getElementsByTagName('note')[0]
print(note.firstChild)
An empty element has no child nodes, so firstChild is
None and note.firstChild.data would raise an
AttributeError. The helper returns an empty string
instead.
$ python element_text.py 'Read ' 'Read this twice.a < b' None ''
Navigating the tree
Each node has links to its parent, its children, and its siblings.
from xml.dom import minidom
from xml.dom.minidom import Node
def next_element(node):
node = node.nextSibling
while node is not None and node.nodeType != Node.ELEMENT_NODE:
node = node.nextSibling
return node
doc = minidom.parse('products.xml')
name = doc.getElementsByTagName('name')[3]
print('name:', name.firstChild.data)
print('parent:', name.parentNode.tagName, name.parentNode.getAttribute('id'))
print('nextSibling:', repr(name.nextSibling.data))
sibling = next_element(name)
while sibling is not None:
print('next element:', sibling.tagName, sibling.firstChild.data)
sibling = next_element(sibling)
root = doc.documentElement
print('root parent:', root.parentNode.nodeName)
print('last child:', repr(root.lastChild.data))
The program starts at the fourth name element and moves
around it.
print('parent:', name.parentNode.tagName, name.parentNode.getAttribute('id'))
print('nextSibling:', repr(name.nextSibling.data))
The parentNode attribute is the enclosing element. The
nextSibling of the name is not the price
element but the whitespace between them.
def next_element(node):
node = node.nextSibling
while node is not None and node.nodeType != Node.ELEMENT_NODE:
node = node.nextSibling
return node
The helper skips over non-element siblings. It returns
None after the last element.
print('root parent:', root.parentNode.nodeName)
The parent of the root element is the document node.
$ python navigation.py name: Honey parent: product 4 nextSibling: '\n ' next element: price 6.75 next element: quantity 8 root parent: #document last child: '\n'
Attributes
Attributes are read and written with methods of the element, or through
its attributes map.
from xml.dom import minidom
doc = minidom.parseString('<product id="3" category="food"/>')
product = doc.documentElement
print(repr(product.getAttribute('id')))
print(repr(product.getAttribute('discount')))
print(product.hasAttribute('discount'))
for name, value in product.attributes.items():
print(f'{name} = {value}')
product.setAttribute('category', 'bakery')
product.setAttribute('note', 'rye & "seeds"')
product.removeAttribute('id')
print(product.toxml())
The program reads, changes, adds, and removes attributes.
print(repr(product.getAttribute('discount')))
print(product.hasAttribute('discount'))
For a missing attribute, getAttribute returns an empty
string, not None. To tell a missing attribute from an
empty one, we use hasAttribute.
for name, value in product.attributes.items():
The attributes property is a NamedNodeMap,
which has an items method like a dictionary.
product.setAttribute('category', 'bakery')
product.setAttribute('note', 'rye & "seeds"')
product.removeAttribute('id')
The setAttribute method changes an existing attribute or
adds a new one. The special characters are escaped when the element is
serialized with toxml.
$ python attributes.py '3' '' False id = 3 category = food <product category="bakery" note="rye & "seeds""/>
Creating a document
In the DOM, all nodes are created by the document they belong to.
from xml.dom import minidom
doc = minidom.Document()
root = doc.createElement('products')
doc.appendChild(root)
product = doc.createElement('product')
product.setAttribute('id', '1')
root.appendChild(product)
name = doc.createElement('name')
name.appendChild(doc.createTextNode('Green tea'))
product.appendChild(name)
price = doc.createElement('price')
price.appendChild(doc.createTextNode('4.50'))
product.appendChild(price)
print(doc.toxml())
The program builds a document with one product.
doc = minidom.Document()
root = doc.createElement('products')
doc.appendChild(root)
We create an empty document and the root element. A new node is not
part of the tree until we append it to a parent with
appendChild.
name = doc.createElement('name')
name.appendChild(doc.createTextNode('Green tea'))
product.appendChild(name)
Text is added as a text node created with
createTextNode. Setting a single child with text takes
three calls.
print(doc.toxml())
The toxml method serializes the document, including the
XML declaration, without any line breaks.
$ python create.py <?xml version="1.0" ?><products><product id="1"><name>Green tea</name><price>4.50</price></product></products>
Writing a file
The writexml method writes the document to an open file.
Its addindent and newl parameters produce
indented output.
from xml.dom import minidom
def add_child(doc, parent, tag, text):
element = doc.createElement(tag)
element.appendChild(doc.createTextNode(text))
parent.appendChild(element)
items = [
('1', 'Green tea', 4.5, 30),
('2', 'Coffee', 7.9, 12),
]
doc = minidom.Document()
root = doc.appendChild(doc.createElement('products'))
for pid, name, price, qty in items:
product = root.appendChild(doc.createElement('product'))
product.setAttribute('id', pid)
add_child(doc, product, 'name', name)
add_child(doc, product, 'price', f'{price:.2f}')
add_child(doc, product, 'quantity', str(qty))
with open('stock.xml', 'w', encoding='utf-8') as f:
doc.writexml(f, addindent=' ', newl='\n', encoding='utf-8')
with open('stock.xml', encoding='utf-8') as f:
print(f.read(), end='')
The program creates two products from a list of tuples and saves them
to stock.xml.
def add_child(doc, parent, tag, text):
element = doc.createElement(tag)
element.appendChild(doc.createTextNode(text))
parent.appendChild(element)
The helper hides the three calls needed for an element with text.
root = doc.appendChild(doc.createElement('products'))
The appendChild method returns the appended node, so we
can create and attach an element in one line.
doc.writexml(f, addindent=' ', newl='\n', encoding='utf-8')
The encoding parameter only adds the encoding to the XML
declaration; the file object itself must be opened with the same
encoding. The toprettyxml method produces the same text as
a string, or as bytes when given an encoding.
$ python write_file.py
<?xml version="1.0" encoding="utf-8"?>
<products>
<product id="1">
<name>Green tea</name>
<price>4.50</price>
<quantity>30</quantity>
</product>
<product id="2">
<name>Coffee</name>
<price>7.90</price>
<quantity>12</quantity>
</product>
</products>
Blank lines in toprettyxml
Pretty-printing a parsed document gives an ugly result. The whitespace
text nodes from the original file are kept, and
toprettyxml adds its own indentation around them.
from xml.dom import minidom
from xml.dom.minidom import Node
data = """<products>
<product id="1">
<name>Green tea</name>
</product>
</products>"""
doc = minidom.parseString(data)
print(doc.toprettyxml(indent=' '), end='')
def strip_blanks(node):
for child in list(node.childNodes):
if child.nodeType == Node.TEXT_NODE and not child.data.strip():
node.removeChild(child)
elif child.nodeType == Node.ELEMENT_NODE:
strip_blanks(child)
strip_blanks(doc)
print(doc.toprettyxml(indent=' '), end='')
The program pretty-prints an indented document before and after removing the whitespace nodes.
def strip_blanks(node):
for child in list(node.childNodes):
if child.nodeType == Node.TEXT_NODE and not child.data.strip():
node.removeChild(child)
elif child.nodeType == Node.ELEMENT_NODE:
strip_blanks(child)
The function removes text nodes that contain only whitespace and
descends into child elements. It iterates over a copy of
childNodes, because removing nodes from the live list
while iterating over it would skip some of them.
$ python blank_lines.py
<?xml version="1.0" ?>
<products>
<product id="1">
<name>Green tea</name>
</product>
</products>
<?xml version="1.0" ?>
<products>
<product id="1">
<name>Green tea</name>
</product>
</products>
Modifying a document
In this example we raise the prices, remove the products that are out of stock, and insert a new product at the beginning.
from xml.dom import minidom
from xml.dom.minidom import Node
def strip_blanks(node):
for child in list(node.childNodes):
if child.nodeType == Node.TEXT_NODE and not child.data.strip():
node.removeChild(child)
elif child.nodeType == Node.ELEMENT_NODE:
strip_blanks(child)
doc = minidom.parse('products.xml')
strip_blanks(doc)
root = doc.documentElement
for price in doc.getElementsByTagName('price'):
price.firstChild.data = f'{float(price.firstChild.data) * 1.1:.2f}'
for product in root.getElementsByTagName('product'):
qty = product.getElementsByTagName('quantity')[0]
if qty.firstChild.data == '0':
root.removeChild(product).unlink()
milk = doc.createElement('product')
milk.setAttribute('id', '6')
milk.appendChild(doc.createElement('name')).appendChild(
doc.createTextNode('Milk'))
root.insertBefore(milk, root.firstChild)
print(root.toprettyxml(indent=' '), end='')
We strip the whitespace nodes first, so that the result can be
pretty-printed and firstChild points to an element.
for price in doc.getElementsByTagName('price'):
price.firstChild.data = f'{float(price.firstChild.data) * 1.1:.2f}'
To change the text, we assign to the data attribute of the
text node.
root.removeChild(product).unlink()
The removeChild method detaches a node and returns it. The
getElementsByTagName method returns a plain list, so
removing nodes in the loop is safe. The unlink method
breaks the internal references of a node we no longer need, which helps
the garbage collector free large trees.
milk.appendChild(doc.createElement('name')).appendChild(
doc.createTextNode('Milk'))
root.insertBefore(milk, root.firstChild)
Because appendChild returns its argument, the calls can be
chained. The insertBefore method inserts a node in front of
an existing child.
$ python modify.py
<products>
<product id="6">
<name>Milk</name>
</product>
<product id="1" category="drinks">
<name>Green tea</name>
<price>4.95</price>
<quantity>30</quantity>
</product>
<product id="2" category="drinks">
<name>Coffee</name>
<price>8.69</price>
<quantity>12</quantity>
</product>
<product id="4" category="food">
<name>Honey</name>
<price>7.43</price>
<quantity>8</quantity>
</product>
</products>
Cloning and replacing nodes
The cloneNode method copies a node, and
replaceChild swaps one child for another.
from xml.dom import minidom
doc = minidom.parseString(
'<menu><dish id="1"><name>Soup</name><price>3.20</price></dish></menu>')
root = doc.documentElement
soup = root.firstChild
shallow = soup.cloneNode(False)
print('shallow:', shallow.toxml())
copy = soup.cloneNode(True)
copy.setAttribute('id', '2')
copy.getElementsByTagName('name')[0].firstChild.data = 'Stew'
print('parent of copy:', copy.parentNode)
root.appendChild(copy)
print(root.toxml())
salad = doc.createElement('dish')
salad.setAttribute('id', '3')
root.replaceChild(salad, soup)
print(root.toxml())
The program copies a dish, changes the copy, and then replaces the original.
shallow = soup.cloneNode(False)
A shallow copy contains the element and its attributes, but no children.
copy = soup.cloneNode(True)
copy.setAttribute('id', '2')
copy.getElementsByTagName('name')[0].firstChild.data = 'Stew'
A deep copy includes all descendants. It is independent of the original and has no parent until we append it somewhere.
root.replaceChild(salad, soup)
The new node comes first, the node to be replaced second.
$ python clone.py shallow: <dish id="1"/> parent of copy: None <menu><dish id="1"><name>Soup</name><price>3.20</price></dish><dish id="2"><name>Stew</name><price>3.20</price></dish></menu> <menu><dish id="3"/><dish id="2"><name>Stew</name><price>3.20</price></dish></menu>
Comments, CDATA, and processing instructions
Unlike ElementTree's default parser, minidom keeps comments and processing instructions, and it can create CDATA sections.
from xml.dom import minidom
doc = minidom.Document()
doc.appendChild(doc.createProcessingInstruction(
'xml-stylesheet', 'type="text/xsl" href="report.xsl"'))
root = doc.appendChild(doc.createElement('report'))
root.appendChild(doc.createComment(' generated daily '))
code = root.appendChild(doc.createElement('code'))
code.appendChild(doc.createCDATASection('if (a < b && b > c) {}'))
text = doc.toxml()
print(text)
parsed = minidom.parseString(text)
for node in parsed.childNodes + parsed.documentElement.childNodes:
print(node.nodeType, node.nodeName)
cdata = parsed.getElementsByTagName('code')[0].firstChild
print(cdata.nodeName, repr(cdata.data))
The program creates a document with all three kinds of nodes and parses it back.
doc.appendChild(doc.createProcessingInstruction(
'xml-stylesheet', 'type="text/xsl" href="report.xsl"'))
A processing instruction has a target and data. This one links an XSLT stylesheet to the document. It is added before the root element.
code.appendChild(doc.createCDATASection('if (a < b && b > c) {}'))
The text of a CDATA section is written without escaping, which keeps code samples readable in the file.
for node in parsed.childNodes + parsed.documentElement.childNodes:
print(node.nodeType, node.nodeName)
After parsing, the processing instruction is a child of the document
(type 7), and the comment (type 8) is a child of the root. The CDATA
section is kept as a separate node, and its data is the
unescaped string.
$ python special_nodes.py
<?xml version="1.0" ?><?xml-stylesheet type="text/xsl" href="report.xsl"?><report><!-- generated daily --><code><![CDATA[if (a < b && b > c) {}]]></code></report>
7 xml-stylesheet
1 report
8 #comment
1 code
#cdata-section 'if (a < b && b > c) {}'
Namespaces
The minidom parser is namespace-aware. Elements keep the prefix from the file and also know their namespace URI.
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/">
<title>Release notes</title>
<entry>
<title>Version 2.1</title>
<media:thumbnail url="v21.png"/>
</entry>
<entry>
<title>Version 2.0</title>
<media:thumbnail url="v20.png"/>
</entry>
</feed>
The feed uses a default namespace and the media prefix.
from xml.dom import minidom
ATOM = 'http://www.w3.org/2005/Atom'
MEDIA = 'http://search.yahoo.com/mrss/'
doc = minidom.parse('feed.xml')
thumb = doc.getElementsByTagName('media:thumbnail')[0]
print(thumb.tagName, thumb.prefix, thumb.localName, thumb.namespaceURI)
for entry in doc.getElementsByTagNameNS(ATOM, 'entry'):
title = entry.getElementsByTagNameNS(ATOM, 'title')[0]
thumb = entry.getElementsByTagNameNS(MEDIA, 'thumbnail')[0]
print(title.firstChild.data, thumb.getAttribute('url'))
new = minidom.Document()
feed = new.appendChild(new.createElementNS(ATOM, 'feed'))
print(new.toxml())
feed.setAttribute('xmlns', ATOM)
print(new.toxml())
The program reads the namespace information and then creates a namespaced element.
thumb = doc.getElementsByTagName('media:thumbnail')[0]
print(thumb.tagName, thumb.prefix, thumb.localName, thumb.namespaceURI)
The getElementsByTagName method matches the name as
written in the file, including the prefix. This breaks when another
document uses a different prefix.
for entry in doc.getElementsByTagNameNS(ATOM, 'entry'):
The getElementsByTagNameNS method matches by namespace URI
and local name, independent of the prefix.
feed = new.appendChild(new.createElementNS(ATOM, 'feed'))
print(new.toxml())
feed.setAttribute('xmlns', ATOM)
The createElementNS method sets the namespace of the
element, but minidom does not write namespace declarations by itself.
We must add the xmlns attribute ourselves, otherwise the
output loses the namespace.
$ python namespaces.py media:thumbnail media thumbnail http://search.yahoo.com/mrss/ Version 2.1 v21.png Version 2.0 v20.png <?xml version="1.0" ?><feed/> <?xml version="1.0" ?><feed xmlns="http://www.w3.org/2005/Atom"/>
Parse errors
The minidom module uses the Expat parser, and malformed documents raise
ExpatError from xml.parsers.expat.
from xml.dom import minidom
from xml.parsers.expat import ExpatError, errors
documents = [
'<a><b>text</b></a>',
'<a><b>text</a>',
'<a>Tom & Jerry</a>',
'<a>\n <b>\n</a>',
]
for doc in documents:
try:
root = minidom.parseString(doc).documentElement
print('ok:', root.tagName)
except ExpatError as e:
print(f'line {e.lineno}, column {e.offset}: {errors.messages[e.code]}')
The program parses one correct and three malformed documents.
except ExpatError as e:
print(f'line {e.lineno}, column {e.offset}: {errors.messages[e.code]}')
The lineno attribute is the line number starting from 1,
and offset is the zero-based column. The
errors.messages dictionary turns the numeric error code
into a message. In the last document, the parser reports the error at
</a>, where it expected the end tag of
b.
As with the other XML parsers of the standard library, see the XML security notes before parsing untrusted documents.
$ python errors.py ok: a line 1, column 12: mismatched tag line 1, column 8: not well-formed (invalid token) line 3, column 2: mismatched tag
Source
xml.dom.minidom – Minimal DOM implementation, xml.dom – The Document Object Model API, XML security
In this article we have parsed XML into a DOM tree, walked its nodes
and siblings, read element text and attributes, created, written, and
pretty-printed documents, removed the whitespace nodes that spoil
toprettyxml, modified, cloned, and replaced nodes, created
comments, CDATA sections, and processing instructions, worked with
namespaces, and handled parse errors. See also
Python ElementTree,
Python XML SAX, and
Python lxml.
Author
List all Python tutorials.