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

如何将XML格式数据读取为键值对格式并提取子节点键值

将XML子节点转为键值对列表

原始XML内容

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<example></example>
</note>

实现代码(Python)

import xml.etree.ElementTree as ET

# 解析目标XML内容
xml_content = """
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<example></example>
</note>
"""
root = ET.fromstring(xml_content)

# 遍历子节点生成键值对列表
result = []
for child in root:
    # 处理空节点的文本,将None转为空字符串
    text = child.text.strip() if child.text is not None else ""
    result.append([child.tag, text])

# 输出指定格式的结果
print(result)

运行结果

[['to', 'Tove'], ['from', 'Jani'], ['heading', 'Reminder'], ['body', "Don't forget me this weekend!"], ['example', '']]

说明

  • 自动跳过根节点<note>,仅处理其直接子节点
  • 空节点<example>的文本会被转为空字符串,完全匹配需求格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:39:51