Python XML ElementTree 修改元素属性:使用 set 方法
使用 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')
代码说明:
- 导入库: 使用
import xml.etree.ElementTree as ET导入 ElementTree 库。 - 解析 XML 文件: 使用
ET.parse('example.xml')解析名为example.xml的 XML 文件。 - 获取根元素: 使用
tree.getroot()获取 XML 文件的根元素。 - 查找元素: 使用
root.find("person[@name='Alice']")查找名为Alice的person元素。 - 修改属性: 使用
alice.set('age', '26')将alice元素的age属性修改为26。 - 保存修改: 使用
tree.write('example.xml')将修改后的 XML 内容写回到example.xml文件中。
通过以上步骤,我们就成功地修改了 XML 文件中元素的属性值。
原文地址: https://www.cveoy.top/t/topic/oBjM 著作权归作者所有。请勿转载和采集!