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 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
解析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}")
</p>
<H3>2. 查找和访问元素</H3>
<p>ElementTree支持简单的路径查找语法:</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2061" title="卡奥斯智能交互引擎"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680098258140.png" alt="卡奥斯智能交互引擎" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2061" title="卡奥斯智能交互引擎">卡奥斯智能交互引擎</a>
<p>聚焦工业领域的AI搜索引擎工具</p>
</div>
<a href="/ai/2061" title="卡奥斯智能交互引擎" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
<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)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)
</p>
<H3>4. 保存修改后的XML</H3>
<p>使用<code>tree.write()</code>将更改写回文件。</p>
<p>
```python
tree.write('updated_data.xml', encoding='utf-8', xml_declaration=True)参数说明:
- encoding:指定编码格式
-
xml_declaration:是否包含XML声明(如
<?xml version="1.0"?>)
基本上就这些。ElementTree适合处理结构清晰、中小型的XML文件,语法简洁,易于上手。对于复杂场景可考虑lxml库,但ElementTree已能满足大多数日常需求。









