ZetCode

Python ElementTree

最后修改:2025 年 2 月 15 日

在本文中,我们将展示如何在 Python 中使用 ElementTree 模块进行 XML 解析和创建。ElementTree 模块提供了简单而高效的 API 来处理 XML 数据。它是 Python 标准库的一部分,被广泛用于 XML 处理。

ElementTree 模块在读取、写入和修改 XML 文件等任务中特别有用。

主要特点

使用 ElementTree 解析 XML

以下示例演示了如何使用 ElementTree 解析 XML 文档。

main.py
import xml.etree.ElementTree as ET

# 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>
    <product>
        <id>3</id>
        <name>Product 3</name>
        <price>24.59</price>
        <quantity>350</quantity>
    </product>
    <product>
        <id>4</id>
        <name>Product 4</name>
        <price>9.9</price>
        <quantity>650</quantity>
    </product>
    <product>
        <id>5</id>
        <name>Product 5</name>
        <price>45</price>
        <quantity>290</quantity>
    </product>
</products>
"""

# Parse the XML data
root = ET.fromstring(xml_data)

# Iterate over product elements
for product in root.findall('product'):

    id = product.find('id').text
    name = product.find('name').text
    price = product.find('price').text
    quantity = product.find('quantity').text
    print(f"Id: {id}, Name: {name}, Price: {price}, Quantity: {quantity}")

在此程序中,使用 ET.fromstring 函数来解析 XML 数据。使用 findall 方法查找所有 product 元素,并使用 find 方法提取 idnamepricequantity 标签的值。

$ python main.py
Id: 1, Name: Product 1, Price: 10.99, Quantity: 30
Id: 2, Name: Product 2, Price: 20.99, Quantity: 130
Id: 3, Name: Product 3, Price: 24.59, Quantity: 350
Id: 4, Name: Product 4, Price: 9.9, Quantity: 650
Id: 5, Name: Product 5, Price: 45, Quantity: 290

使用 ElementTree 修改 XML

以下示例演示了如何使用 ElementTree 修改 XML 文档。

main.py
import xml.etree.ElementTree as ET

# 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
root = ET.fromstring(xml_data)

# Modify the first product's price
first_product = root.find('product')
first_product.find('price').text = '15.99'

# Add a new product
new_product = ET.Element('product')
ET.SubElement(new_product, 'id').text = '3'
ET.SubElement(new_product, 'name').text = 'Product 3'
ET.SubElement(new_product, 'price').text = '30.99'
ET.SubElement(new_product, 'quantity').text = '200'
root.append(new_product)

# Print the modified XML
print(ET.tostring(root, encoding='unicode'))

在此程序中,使用 find 方法定位第一个 product 元素,并修改其 price。使用 ET.ElementET.SubElement 创建新的 product 元素,并将其附加到根元素。使用 ET.tostring 打印修改后的 XML。

读取带有 id 属性的 XML 文件

以下示例演示了如何读取一个 XML 文件,其中每个 product 元素都具有 id 属性。该程序提取 id 属性以及 namepricequantity 的值。

products.xml
<products>
    <product id="1">
        <name>Product 1</name>
        <price>10.99</price>
        <quantity>30</quantity>
    </product>
    <product id="2">
        <id>2</id>
        <name>Product 2</name>
        <price>20.99</price>
        <quantity>130</quantity>
    </product>
    <product id="3">
        <name>Product 3</name>
        <price>24.59</price>
        <quantity>350</quantity>
    </product>
    <product id="4">
        <name>Product 4</name>
        <price>9.9</price>
        <quantity>650</quantity>
    </product>
    <product id="5">
        <name>Product 5</name>
        <price>45</price>
        <quantity>290</quantity>
    </product>
</products>

我们的产品 id 是作为属性存在的。

main.py
import xml.etree.ElementTree as ET


file_name = 'products.xml'

tree = ET.parse(file_name)
root = tree.getroot()

# Iterate over product elements
for product in root.findall('product'):
    # Extract the id attribute
    product_id = product.get('id')
    name = product.find('name').text
    price = product.find('price').text
    quantity = product.find('quantity').text
    print(f"Id: {product_id}, Name: {name}, Price: {price}, Quantity: {quantity}")
tree = ET.parse(file_name)
root = tree.getroot()

我们使用 parse 方法解析文档,并使用 getroot 方法获取文档的根。

product_id = product.get('id')
name = product.find('name').text
price = product.find('price').text
quantity = product.find('quantity').text

使用 get 方法从每个 product 元素提取 id 属性。使用 find 方法提取 namepricequantity 的值。

$ python main.py
Id: 1, Name: Product 1, Price: 10.99, Quantity: 30
Id: 2, Name: Product 2, Price: 20.99, Quantity: 130
Id: 3, Name: Product 3, Price: 24.59, Quantity: 350
Id: 4, Name: Product 4, Price: 9.9, Quantity: 650
Id: 5, Name: Product 5, Price: 45, Quantity: 290

使用 ElementTree 编写 XML

以下示例演示了如何使用 ElementTree 创建和编写 XML 文档。

main.py
import xml.etree.ElementTree as ET

# Create the root element
root = ET.Element('products')

# Create product elements
product1 = ET.SubElement(root, 'product')
ET.SubElement(product1, 'id').text = '1'
ET.SubElement(product1, 'name').text = 'Product 1'
ET.SubElement(product1, 'price').text = '10.99'
ET.SubElement(product1, 'quantity').text = '30'

product2 = ET.SubElement(root, 'product')
ET.SubElement(product2, 'id').text = '2'
ET.SubElement(product2, 'name').text = 'Product 2'
ET.SubElement(product2, 'price').text = '20.99'
ET.SubElement(product2, 'quantity').text = '130'

# Function to pretty-print XML
def prettify(element, level=0):
    indent = '  '
    if len(element):
        if not element.text or not element.text.strip():
            element.text = '\n' + indent * (level + 1)
        for elem in element:
            prettify(elem, level + 1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = '\n' + indent * (level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = '\n' + indent * level
    else:
        if level and (not element.tail or not element.tail.strip()):
            element.tail = '\n' + indent * level
    return element

# Pretty-print the XML
pretty_root = prettify(root)

# Create an ElementTree object
tree = ET.ElementTree(pretty_root)

# Write the pretty-printed XML to a file
tree.write('products2.xml', encoding='utf-8', xml_declaration=True)

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

在此程序中,使用 ET.ElementET.SubElement 函数创建 XML 结构。使用 tree.write 方法将 XML 数据写入文件。

使用 prettify 函数对 XML 数据进行整齐的缩进。

来源

Python ElementTree - 文档

在本文中,我们展示了如何在 Python 中使用 ElementTree 模块进行 XML 解析、修改和创建。ElementTree 模块是处理 XML 数据的强大工具。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程