如何使用Python的xml模块修改XML文档中的某个节点?

# 使用Python的xml模块修改XML文档中的某个节点
import xml.etree.ElementTree as ET

# 1. 解析XML文件
# 示例XML内容如下:
xml_content = '''
<root>
    <person id="1">
        <name>Alice</name>
        <age>25</age>
    </person>
    <person id="2">
        <name>Bob</name>
        <age>30</age>
    </person>
</root>
'''

# 将XML内容写入临时文件(实际场景中可能是从文件加载)
with open('test.xml', 'w') as f:
    f.write(xml_content)

# 加载XML文件
tree = ET.parse('test.xml')
root = tree.getroot()

# 2. 修改XML节点
# 示例:将id为2的person节点的name修改为"Charlie"
for person in root.findall('person'):
    if person.get('id') == '2':
        name_node = person.find('name')
        if name_node is not None:
            name_node.text = "Charlie"

# 3. 保存修改后的XML文件
# 使用ElementTree的write方法保存修改后的内容
tree.write('modified.xml', encoding='utf-8', xml_declaration=True)

# 查看修改后的XML文件
with open('modified.xml', 'r') as f:
    modified_content = f.read()

print("修改后的XML内容:")
print(modified_content)

# 输出示例:
# <root>
#     <person id="1">
#         <name>Alice</name>
#         <age>25</age>
#     </person>
#     <person id="2">
#         <name>Charlie</name>
#         <age>30</age>
#     </person>
# </root>

# 扩展说明:
# - `findall`方法用于查找所有匹配的节点,`find`方法用于查找第一个匹配的节点。
# - `get`方法用于获取节点的属性值。
# - `text`属性用于获取或设置节点的文本内容。
# - 若需要删除节点,可以使用`remove`方法。

详细说明

  1. 解析XML文件:

    • 使用ET.parse方法加载XML文件,获取ElementTree对象。
    • 通过getroot方法获取根节点。
  2. 查找节点:

    • 使用findall方法遍历所有符合条件的节点(如person)。
    • 通过get方法检查节点的属性(如id),确认是否为需要修改的节点。
  3. 修改节点内容:

    • 使用find方法定位需要修改的子节点(如name)。
    • 直接修改其text属性即可完成内容更新。
  4. 保存修改:

    • 调用write方法将修改后的内容保存到文件,同时可以指定编码和声明(如xml_declaration=True)。
  5. 其他操作:

    • 若要添加节点,可以使用ET.SubElement方法。
    • 若要删除节点,可以调用父节点的remove方法。

示例场景

假设需要为id为1的person节点添加一个gender子节点:

for person in root.findall('person'):
    if person.get('id') == '1':
        gender_node = ET.SubElement(person, 'gender')
        gender_node.text = "Female"

tree.write('modified_with_gender.xml', encoding='utf-8')

通过以上方法,可以灵活地对XML文档进行增删改查操作。