使用xml.etree.ElementTree删除XML元素出现AttributeError报错如何解决
报错原因
这个报错属于典型的拼写错误:你调用的ET.ElimentTree不是该库提供的合法类名,正确类名为ET.ElementTree,你将类名中的字母e错误写为i,导致Python在库中找不到对应属性抛出AttributeError。
其他隐藏问题
除了上述直接报错的拼写问题,你的代码还存在另外几个会导致运行失败的问题:
- 写入文件时调用的
trre.write()存在拼写错误,正确变量名是tree - 打开文件时使用的
filename变量没有提前赋值,运行时会抛出NameError - 额外冗余操作:修改完根节点内容后,不需要重新实例化
ElementTree对象,原有tree已经和根节点绑定,直接调用写入方法即可
修复后可运行代码
import xml.etree.ElementTree as ET # 统一声明文件路径,避免硬编码不一致 xml_path = 'C:\\Ashok\\sample.xml' tree = ET.ElementTree(file=xml_path) root = tree.getroot() DisabledFeatureListForCountry = root.find('.//DisabledFeatureListForCountry') for DisabledFeatureDetails in DisabledFeatureListForCountry.findall('DisabledFeatureDetails'): country_node = DisabledFeatureDetails.find('Country') if country_node.text == "Australia": DisabledFeatureListForCountry.remove(DisabledFeatureDetails) # 直接写入修改后的内容即可 with open(xml_path, "wb") as f: tree.write(f)
内容的提问来源于stack exchange,提问作者Ashok Anumula
相关产品推荐
相关产品推荐

