You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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)

关键修改点

  1. 给递归函数find_subcomponents新增indent参数,默认值为0,用来标记当前组件的层级缩进量
  2. 输出组件名称前,用' ' * indent生成对应层级的缩进空格
  3. 递归调用子组件时,将indent参数加1,保证子层级缩进比父层级多一级
  4. 修正子组件查找路径为./COMPONENT,仅查找当前组件的直接子组件(原代码.//COMPONENT会遍历所有后代组件,是导致层级逻辑混乱的核心原因之一)

内容的提问来源于stack exchange,提问作者user22242715

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 04:49:50