如何让XML组件递归遍历输出呈现父子层级树形结构?
解决Python递归查找组件时的层级缩进树形输出问题
问题说明
现有Python代码可递归查找指定COMPONENT的子组件,但输出未体现层级关系,导致x762被误显示为x454的子组件,需修改代码使输出以缩进形式呈现正确的父子层级树形结构。
现有代码
import xml.etree.ElementTree as ET def find_subcomponents(component): print(component.get('NAME')) for child in component.findall('.//COMPONENT'): find_subcomponents(child) # 解析XML tree = ET.parse('components.xml') root = tree.getroot() target = root.find(".//COMPONENT[@NAME='x123']") find_subcomponents(target)
XML示例(components.xml)
<ROOT> <COMPONENT NAME="x123"> <COMPONENT NAME="x454"> <COMPONENT NAME="x678"/> </COMPONENT> <COMPONENT NAME="x762"/> </COMPONENT> </ROOT>
当前错误输出
x123 x454 x678 x762
期望输出
x123 x454 x678 x762
修改后的代码
import xml.etree.ElementTree as ET def find_subcomponents(component, indent=0): # 用缩进体现层级,每级增加2个空格 print(' ' * indent + component.get('NAME')) for child in component.findall('./COMPONENT'): # 递归时缩进+1,实现层级递进 find_subcomponents(child, indent + 1) # 解析XML tree = ET.parse('components.xml') root = tree.getroot() target = root.find(".//COMPONENT[@NAME='x123']") find_subcomponents(target)
关键修改点
- 给递归函数
find_subcomponents新增indent参数,默认值为0,用来标记当前组件的层级缩进量 - 输出组件名称前,用
' ' * indent生成对应层级的缩进空格 - 递归调用子组件时,将
indent参数加1,保证子层级缩进比父层级多一级 - 修正子组件查找路径为
./COMPONENT,仅查找当前组件的直接子组件(原代码.//COMPONENT会遍历所有后代组件,是导致层级逻辑混乱的核心原因之一)
内容的提问来源于stack exchange,提问作者user22242715
相关产品推荐
相关产品推荐

