使用ElementTree将XML转字典时的两个问题求助
解决XML转字典的两个问题(Python 3.9 + xml.etree.ElementTree)
修复后的完整代码
import xml.etree.ElementTree as ET def xml_to_dict(element): result = {} # 处理元素属性 if element.attrib: result.update(element.attrib) # 处理子元素 children = list(element) if children: child_dict = {} for child in children: child_data = xml_to_dict(child) if child.tag in child_dict: # 同标签多子元素转为列表 if not isinstance(child_dict[child.tag], list): child_dict[child.tag] = [child_dict[child.tag]] child_dict[child.tag].append(child_data) else: child_dict[child.tag] = child_data result.update(child_dict) # 处理元素文本,规避None调用strip()的错误 if element.text: text_content = element.text.strip() if text_content: result['text'] = text_content return result # 解析XML文件(替换为你的配置文件路径) tree = ET.parse('legacy_config.xml') root = tree.getroot() # 将根节点作为顶层键加入结果字典 final_dict = {root.tag: xml_to_dict(root)} print(final_dict)
问题1:根节点未出现在字典键中的修复
原代码大概率直接返回了根节点内部的处理结果,未将根节点自身标签作为顶层键。修复时通过{root.tag: xml_to_dict(root)}把根节点标签设为字典的顶层键,对应值为根节点的完整处理结果,确保根节点名称出现在最终字典中。
问题2:自闭合标签触发AttributeError的修复
自闭合标签(如<Data Count="58" />)的element.text属性为None,直接调用strip()会报错。修复逻辑为先判断element.text是否存在,仅当它不为None时才执行strip(),同时只保留非空的文本内容,避免生成无意义的空字符串键值对。
内容的提问来源于stack exchange,提问作者Floren
相关产品推荐
相关产品推荐

