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文件。
使用ElementTree.parse()方法可以加载一个XML文件,返回一个ElementTree对象。通过.getroot()获取根节点,然后遍历子元素。
<?xml version="1.0"?>
<company>
<employee id="1">
<name>张三</name>
<age>30</age>
<department>技术部</department>
</employee>
<employee id="2">
<name>李四</name>
<age>25</age>
<department>销售部</department>
</employee>
</company>
读取代码:
```python import xml.etree.ElementTree as ET
tree = ET.parse('data.xml') root = tree.getroot()
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}")
</p>
<H3>2. 查找和访问元素</H3>
<p>ElementTree支持简单的路径查找语法:</p>
<ul>
<li><strong>find(match)</strong>:返回第一个匹配的子元素</li>
<li><strong>findall(match)</strong>:返回所有匹配的子元素列表</li>
<li><strong>get(attr)</strong>:获取元素属性值</li>
<li><strong>text</strong>:获取元素文本内容</li>
</ul>
<p>例如查找id为2的员工:</p>
<p>
```python
employee = root.find('employee[@id="2"]')
if employee is not None:
print(employee.find('name').text)可以直接修改元素的文本、属性,或添加/删除元素。
立即学习“Python免费学习笔记(深入)”;
```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)
</p>
<H3>4. 保存修改后的XML</H3>
<p>使用<code>tree.write()</code>将更改写回文件。</p>
<p>
```python
tree.write('updated_data.xml', encoding='utf-8', xml_declaration=True)参数说明:
<?xml version="1.0"?>)基本上就这些。ElementTree适合处理结构清晰、中小型的XML文件,语法简洁,易于上手。对于复杂场景可考虑lxml库,但ElementTree已能满足大多数日常需求。
以上就是Python如何处理xml数据 使用ElementTree模块读取和修改xml的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号