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

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

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

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

1. 读取XML文件

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

示例XML文件(data.xml):
<?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>
<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>
                    <div class="aritcle_card">
                        <a class="aritcle_card_img" href="/ai/2364">
                            <img src="https://img.php.cn/upload/ai_manual/001/246/273/176179449590268.png" alt="iSlide PPT">
                        </a>
                        <div class="aritcle_card_info">
                            <a href="/ai/2364">iSlide PPT</a>
                            <p>DeepSeek AI加持,输入主题生成专业PPT,支持Word/PDF等45种文档导入,职场汇报、教学提案轻松搞定</p>
                            <div class="">
                                <img src="/static/images/card_xiazai.png" alt="iSlide PPT">
                                <span>375</span>
                            </div>
                        </div>
                        <a href="/ai/2364" class="aritcle_card_btn">
                            <span>查看详情</span>
                            <img src="/static/images/cardxiayige-3.png" alt="iSlide PPT">
                        </a>
                    </div>
                
<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已能满足大多数日常需求。

以上就是Python如何处理xml数据 使用ElementTree模块读取和修改xml的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。