ZetCode

Python minidom

最后修改于 2025 年 3 月 7 日

在本文中,我们将展示如何在 Python 中使用 minidom 模块进行 XML 解析和创建。minidom 模块为 XML 提供了一个轻量级的 DOM 接口,它是 Python 标准库的一部分。

minidom 模块可用于使用基于 DOM 的方法读取、写入和修改 XML 文档。

主要特性

使用 minidom 解析 XML

此示例展示了如何使用 minidom 解析 XML 文档。

main.py
from xml.dom import minidom

# XML data
xml_data = """
<products>
    <product>
        <id>1</id>
        <name>Product 1</name>
        <price>10.99</price>
        <quantity>30</quantity>
    </product>
    <product>
        <id>2</id>
        <name>Product 2</name>
        <price>20.99</price>
        <quantity>130</quantity>
    </product>
</products>
"""

# Parse the XML data
doc = minidom.parseString(xml_data)

# Get all product elements
products = doc.getElementsByTagName('product')

# Iterate over product elements
for product in products:
    id = product.getElementsByTagName('id')[0].firstChild.data
    name = product.getElementsByTagName('name')[0].firstChild.data
    price = product.getElementsByTagName('price')[0].firstChild.data
    qty = product.getElementsByTagName('quantity')[0].firstChild.data
    print(f"Id: {id}, Name: {name}, Price: {price}, Quantity: {qty}")

在此,parseString 将 XML 字符串解析为 DOM 对象。我们使用 getElementsByTagName 查找元素,并使用 firstChild.data 提取其文本。

$ python main.py
Id: 1, Name: Product 1, Price: 10.99, Quantity: 30
Id: 2, Name: Product 2, Price: 20.99, Quantity: 130

使用 minidom 修改 XML

此示例展示了如何使用 minidom 修改 XML 文档。

main.py
from xml.dom import minidom

# XML data
xml_data = """
<products>
    <product>
        <id>1</id>
        <name>Product 1</name>
        <price>10.99</price>
        <quantity>30</quantity>
    </product>
</products>
"""

# Parse the XML data
doc = minidom.parseString(xml_data)

# Modify the first product's price
product = doc.getElementsByTagName('product')[0]
price = product.getElementsByTagName('price')[0]
price.firstChild.data = '15.99'

# Add a new product
new_product = doc.createElement('product')
doc.documentElement.appendChild(new_product)
for tag, text in [('id', '2'), ('name', 'Product 2'), 
                  ('price', '30.99'), ('quantity', '200')]:
    elem = doc.createElement(tag)
    elem.appendChild(doc.createTextNode(text))
    new_product.appendChild(elem)

# Print the modified XML
print(doc.toprettyxml(indent="  "))

我们通过更新 firstChild.data 来修改价格。 使用 createElement 创建一个新产品,并使用 createTextNode 添加文本节点。

使用 id 属性读取 XML 文件

此示例使用 minidom 读取带有 id 属性的 XML 文件。

products.xml
<products>
    <product id="1">
        <name>Product 1</name>
        <price>10.99</price>
        <quantity>30</quantity>
    </product>
    <product id="2">
        <name>Product 2</name>
        <price>20.99</price>
        <quantity>130</quantity>
    </product>
</products>

产品具有 id 作为属性。

main.py
from xml.dom import minidom

file_name = 'products.xml'

# Parse the XML file
doc = minidom.parse(file_name)
products = doc.getElementsByTagName('product')

# Iterate over product elements
for product in products:
    product_id = product.getAttribute('id')
    name = product.getElementsByTagName('name')[0].firstChild.data
    price = product.getElementsByTagName('price')[0].firstChild.data
    qty = product.getElementsByTagName('quantity')[0].firstChild.data
    print(f"Id: {product_id}, Name: {name}, Price: {price}, Quantity: {qty}")

我们使用 getAttribute 提取 id 属性,并使用 firstChild.data 获取元素文本。

$ python main.py
Id: 1, Name: Product 1, Price: 10.99, Quantity: 30
Id: 2, Name: Product 2, Price: 20.99, Quantity: 130

使用 minidom 写入 XML

此示例使用 minidom 创建和写入 XML 文档。

main.py
from xml.dom import minidom

# Create the document
doc = minidom.Document()

# Create the root element
root = doc.createElement('products')
doc.appendChild(root)

# Create product elements
for i, (name, price, qty) in enumerate([
    ('Product 1', '10.99', '30'),
    ('Product 2', '20.99', '130')
], 1):
    product = doc.createElement('product')
    root.appendChild(product)
    for tag, text in [('id', str(i)), ('name', name), 
                      ('price', price), ('quantity', qty)]:
        elem = doc.createElement(tag)
        elem.appendChild(doc.createTextNode(text))
        product.appendChild(elem)

# Write to file with pretty printing
with open('products2.xml', 'w', encoding='utf-8') as f:
    f.write(doc.toprettyxml(indent="  "))

print("XML file created successfully with proper indentation.")

我们使用 createElementcreateTextNode 构建 XML 结构,然后使用 toprettyxml 写入它。

来源

Python minidom - 文档

本文演示了如何在 Python 中使用 minidom 模块进行 XML 解析、修改和创建。

作者

我叫 Jan Bodnar,是一位拥有多年经验的热情程序员。 自 2007 年以来,我一直在撰写编程文章,迄今为止已发表超过 1400 篇文章和 8 本电子书。

列出所有 Python 教程