信息发布→ 登录 注册 退出

Python如何处理xml数据 使用ElementTree模块读取和修改xml

发布时间:2025-11-16

点击量:
Python中处理XML最常用ElementTree模块。1. 用ET.parse()读取XML文件,getroot()获取根节点并遍历子元素;2. 使用find()/findall()查找元素,get()获取属性,text获取文本内容;3. 可修改元素文本、属性,添加或删除节点;4. 通过tree.write()保存修改后的XML文件。该方法适用于中小型结构化XML数据处理。

Python中处理XML数据最常用的方式是使用内置的xml.etree.ElementTree模块(简称ElementTree)。它提供了一种简单高效的方式来解析、读取、修改和生成XML文件。

1. 读取XML文件

使用ElementTree.parse()方法可以加载一个XML文件,返回一个ElementTree对象。通过.getroot()获取根节点,然后遍历子元素。

示例XML文件(data.xml):


  
    张三
    30
    技术部
  
  
    李四
    25
    销售部
  

读取代码:

```python import xml.etree.ElementTree as ET

解析XML文件

tree = ET.parse('data.xml') root = tree.getroot()

遍历所有employee元素

for employee in root.findall('employee'): name = employee.find('name').text age = employee.find('age').text dept = employee.find('department').text emp_id = employee.get('id') print(f"ID: {emp_id}, 姓名: {name}, 年龄: {age}, 部门: {dept}")

2. 查找和访问元素

ElementTree支持简单的路径查找语法:

  • find(match):返回第一个匹配的子元素
  • findall(match):返回所有匹配的子元素列表
  • get(attr):获取元素属性值
  • text:获取元素文本内容

例如查找id为2的员工:

```python employee = root.find('employee[@id="2"]') if employee is not None: print(employee.find('name').text)

3. 修改XML数据

可以直接修改元素的文本、属性,或添加/删除元素。

```python # 修改某个员工的年龄 for employee in root.findall('employee'): if employee.get('id') == '1': age_elem = employee.find('age') age_elem.text = '31' # 更新年龄

添加新员工

new_emp = ET.SubElement(root, 'employee', attrib={'id': '3'}) ET.SubElement(new_emp, 'name').text = '王五' ET.SubElement(new_emp, 'age').text = '28' ET.SubElement(new_emp, 'department').text = '人事部'

删除某个员工

for employee in root.findall('employee'): if employee.get('id') == '2': root.remove(employee)

4. 保存修改后的XML

使用tree.write()将更改写回文件。

```python tree.write('updated_data.xml', encoding='utf-8', xml_declaration=True)

参数说明:

  • encoding:指定编码格式
  • xml_declaration:是否包含XML声明(如

基本上就这些。ElementTree适合处理结构清晰、中小型的XML文件,语法简洁,易于上手。对于复杂场景可考虑lxml库,但ElementTree已能满足大多数日常需求。

标签:# python  # 编码  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!