Python中根据XML子元素取值修改另一对应子元素值的实现问题
问题原因与解决方案
核心错误点
replace方法使用不符合lxml的API要求:Element.replace()的入参要求是旧节点对象、新节点对象,你传入的第一个参数是字符串'path',API无法识别匹配对应节点,因此没有修改效果。- 可选优化:确实不需要新建节点完成替换,直接修改目标节点的
text属性是更简洁可靠的方案,不会打乱原XML的节点结构、缩进属性。
推荐实现(直接修改节点文本)
items = {'x':'bye', 'y': 'bye_again'} tags = ['input_file','type'] for type_val, new_path_val in items.items(): # 直接通过xpath定位到对应input_file下的path节点 path_node = root.xpath( f'//{tags[0]}[{tags[1]}/text()=$target_val]/path', target_val=type_val )[0] # 直接修改文本内容即可 path_node.text = new_path_val LET.indent(root, space=" ") print(LET.tostring(root).decode())
节点替换写法的修复版
如果你坚持要用节点替换的方式实现,修改后代码如下:
items = {'x':'bye', 'y': 'bye_again'} tags = ['input_file','type'] for v in items.keys(): destination = root.xpath(f'//{tags[0]}/{tags[1]}[text()="{v}"]/..')[0] # 先获取原path节点对象 old_path = destination.find('path') new_elem=LET.fromstring(f'<path>{items[v]}</path>') # 替换方法第一个参数传入旧节点对象 destination.replace(old_path, new_elem) LET.indent(root, space=" ") print(LET.tostring(root).decode())
内容的提问来源于stack exchange,提问作者PhilL
相关产品推荐
相关产品推荐

