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

如何在Python中将XML路径转换为嵌套XML格式

路径转嵌套XML的Python实现

直接提供满足需求的函数,逻辑清晰且符合指定的缩进格式:

def path_to_nested_xml(path, value):
    nodes = path.split('/')
    xml_lines = []
    
    # 写入所有父节点的开始标签
    for i in range(len(nodes)-1):
        indent = ' ' * i
        xml_lines.append(f"{indent}<{nodes[i]}>")
    
    # 写入叶子节点的完整内容(包含值)
    leaf_indent = ' ' * (len(nodes)-1)
    xml_lines.append(f"{leaf_indent}<{nodes[-1]}> {value} </{nodes[-1]}>")
    
    # 倒序写入父节点的闭合标签
    for i in reversed(range(len(nodes)-1)):
        indent = ' ' * i
        xml_lines.append(f"{indent}</{nodes[i]}>")
    
    return '\n'.join(xml_lines)

函数逻辑说明

  1. 拆分路径:将输入的斜杠分隔路径拆分为节点列表(如"a/b/c/d"转为["a", "b", "c", "d"])
  2. 生成开始标签:遍历除叶子节点外的所有节点,按层级添加对应空格缩进,写入开始标签
  3. 生成叶子节点内容:给叶子节点添加对应层级的缩进,写入包含指定值的完整标签
  4. 生成闭合标签:倒序遍历父节点,按对应层级缩进写入闭合标签
  5. 拼接结果:将所有行拼接为最终的XML字符串

测试示例

# 调用函数
output = path_to_nested_xml("a/b/c/d", "Apple")
print(output)

输出结果:

<a>
 <b>
  <c>
   <d> Apple </d>
  </c>
 </b>
</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:50:34