使用 Python 的 xml.etree.ElementTree 库可以轻松修改 XML 文件中元素的属性。

示例:修改 Alice 的年龄

假设我们有以下 XML 文件:

<root>
  <person name='Alice' age='25' />
  <person name='Bob' age='30' />
</root>

我们可以使用以下代码将 Alice 的年龄修改为 26:

import xml.etree.ElementTree as ET

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

alice = root.find("person[@name='Alice']")
alice.set('age', '26')

tree.write('example.xml')

代码说明:

  1. 导入库: 使用 import xml.etree.ElementTree as ET 导入 ElementTree 库。
  2. 解析 XML 文件: 使用 ET.parse('example.xml') 解析名为 example.xml 的 XML 文件。
  3. 获取根元素: 使用 tree.getroot() 获取 XML 文件的根元素。
  4. 查找元素: 使用 root.find("person[@name='Alice']") 查找名为 Alice 的 person 元素。
  5. 修改属性: 使用 alice.set('age', '26') 将 alice 元素的 age 属性修改为 26。
  6. 保存修改: 使用 tree.write('example.xml') 将修改后的 XML 内容写回到 example.xml 文件中。

通过以上步骤,我们就成功地修改了 XML 文件中元素的属性值。

Python XML ElementTree 修改元素属性:使用 set 方法

原文地址: https://www.cveoy.top/t/topic/oBjM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录